【问题标题】:Where do *.d.ts files come from?*.d.ts 文件来自哪里?
【发布时间】:2018-12-22 20:27:49
【问题描述】:

我正在学习 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 文件中不存在 cmets。当我执行npm install underscore 时,它是否已下载到我的计算机上?是否可以转到 js 文件中的函数定义而不是这个(在 VSCode 中)?

【问题讨论】:

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


【解决方案1】:

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

也就是说,在您的项目目录中,您将 npm install --save underscore,然后运行 ​​npm install --save-dev @types/underscore 以访问其他无类型包的类型定义。

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

【讨论】:

  • 这个答案大体上是正确的,但需要指出的是,DefinitelyTyped 作为第三方提供了这些定义。还有许多带有自己定义的 Node 模块。
猜你喜欢
  • 2010-09-26
  • 2023-03-28
  • 2018-12-23
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 2010-09-21
  • 2014-04-24
  • 2015-07-13
相关资源
最近更新 更多