* .d.ts文件来自哪里?

时间:2018-07-14 18:35:05

标签: javascript node.js typescript npm visual-studio-code

我正在学习node.js并使用Visual Studio Code。在我的项目中,我安装了underscore.js。所以我的node_modules文件夹看起来像这样:

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

这是我的index.js文件:

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

现在,当我按Ctrl +单击index.js中的contains函数时,在Visual Studio Code中这意味着“转到定义”,它不会显示包含在node_modules/underscore.js内部的函数。而是打开文件/home/user/.cache/typescript/2.9/node_modules/@types/underscore/index.d.ts

这是一个打字稿文件,不是javascript,我无法理解它来自哪里?我认为它不是从javascript文件自动生成的,因为js文件中不存在注释。执行npm install underscore时,它是否已下载到我的计算机上?可以在js文件中而不是在VSCode中转到函数定义吗?

1 个答案:

答案 0 :(得分:4)

d.ts文件来自以下存储库:https://github.com/DefinitelyTyped/DefinitelyTyped。它们以@ types / package-name发布,并且应作为devDependency安装在您正在使用的文件夹中。

也就是说,在您的项目目录中,您将先npm install --save underscore,然后运行npm install --save-dev @types/underscore来访问本来没有类型的包的类型定义。

它指向TypeScript缓存的原因与Node模块的解析有关。节点在树中查找每个node_modules文件夹,直到找到匹配项为止(更多信息:https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8)。基本上,Node和TypeScript环顾四周,发现了@ types / underscore的缓存版本,只是指向那里,而不是项目中的本地安装版本。

相关问题