2

I'm learning node.js and using Visual Studio Code. In my project I installed underscore.js. So my node_modules folder looks like this:

node_modules/
└── underscore
    ├── LICENSE
    ├── package.json
    ├── README.md
    ├── underscore.js
    ├── underscore-min.js
    └── underscore-min.js.map

and this is my index.js file:

const _ = require('underscore');
console.log(_.contains([1, 2, 3, 4], 2));

Now, when I do Ctrl+Click on the contains function inside index.js which in Visual Studio Code means "Go to definition", it doesn't show contains function inside node_modules/underscore.js. Instead it opens file /home/user/.cache/typescript/2.9/node_modules/@types/underscore/index.d.ts

This is a typescript file, not javascript, and I cannot understand where does it come from? I don't think it's automatically generated from javascript file, because comments there don't exist in js file. Was it downloaded to my computer when I executed npm install underscore? Is it possible to go to function definition in js file instead of this one (in VSCode)?

displayName
  • 986
  • 16
  • 40
  • Possible duplicate of [About "\*.d.ts" in TypeScript](https://stackoverflow.com/questions/21247278/about-d-ts-in-typescript) – Devon Bessemer Jul 14 '18 at 18:40
  • 1
    You have multiple questions wrapped into one here but you should probably tag vscode if you want to ask about that functionality. – Devon Bessemer Jul 14 '18 at 18:42

1 Answers1

5

d.ts files come from this repository: https://github.com/DefinitelyTyped/DefinitelyTyped. They are published under @types/package-name, and should be installed in the folder you're working in as a devDependency.

That is, in your project directory, you would npm install --save underscore, then run npm install --save-dev @types/underscore to get access to the type definitions for an otherwise untyped package.

The reason it points to the TypeScript cache has to do with Node module resolution. Node looks for every node_modules folder up the tree until it finds a match (more info: https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8). Basically, Node and TypeScript looked around, and found a cached versions of @types/underscore, and just point there rather than the locally installed version in your project.

wilsonhobbs
  • 941
  • 8
  • 18
  • 1
    This answer is generally correct, but it should be mentioned that DefinitelyTyped provides these definitions as a third-party. There are also many Node modules that ship with their own definitions. – idleberg Jul 15 '18 at 10:39