从 TypeScript 3.7 开始,TypeScript 新增了使用 JSDoc 语法从 JavaScript 生成 .d.ts 文件的支持。
这种设置意味着你可以获得由 TypeScript 驱动的编辑器的编写体验,而无需将项目迁移到 TypeScript,也不必在代码库中维护 .d.ts 文件。TypeScript 支持大多数 JSDoc 标签,你可以在这里找到参考。
设置项目以输出 .d.ts 文件
要在项目中添加 .d.ts 文件的创建,最多需要完成四个步骤:
- 将 TypeScript 添加到开发依赖
- 添加
tsconfig.json以配置 TypeScript - 运行 TypeScript 编译器,为 JS 文件生成相应的 d.ts 文件
- (可选)编辑 package.json 以引用这些类型
添加 TypeScript
你可以在我们的安装页面了解如何操作。
TSConfig
TSConfig 是一个 jsonc 文件,用于配置编译器标志并声明在哪里查找文件。在本例中,你需要类似下面的文件:
{// Change this to match your project"": ["src/**/*"],"": {// Tells TypeScript to read JS files, as// normally they are ignored as source files"": true,// Generate d.ts files"": true,// This compiler run should// only output d.ts files"": true,// Types should go into this directory.// Removing this would place the .d.ts files// next to the .js files"": "dist",// go to js file when using IDE functions like// "Go to Definition" in VSCode"": true}}
你可以在 tsconfig 参考中进一步了解这些选项。除了使用 TSConfig 文件,也可以使用 CLI,其行为与 CLI 命令相同。
shnpx -p typescript tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types
运行编译器
你可以在我们的安装页面了解如何操作。如果你的文件位于项目的 .gitignore 中,请务必确保这些文件包含在发布的包中。
编辑 package.json
TypeScript 在 package.json 中复刻了 node 的模块解析方式,并增加了一步来查找 .d.ts 文件。大致来说,解析时会先检查可选的 types 字段,然后检查 "main" 字段,最后尝试根目录下的 index.d.ts。
| Package.json | 默认 .d.ts 的位置 |
|---|---|
| 没有“types”字段 | 先检查“main”,然后检查 index.d.ts |
| “types”: “main.d.ts”(指定类型声明文件) | main.d.ts |
| “types”: “./dist/main.js”(指向 JS 文件) | ./dist/main.d.ts |
如果不存在,则使用“main”
| Package.json | 默认 .d.ts 的位置 |
|---|---|
| 没有“main”字段 | index.d.ts |
| “main”:“index.js” | index.d.ts |
| “main”:“./dist/index.js” | ./dist/index.d.ts |