在 tsconfig.json 中启用 declaration 和 declarationMap 的用例是什么?

What is the use-case of enabling declaration and declarationMap in tsconfig.json?

如果我们启用允许我们在浏览器上调试的sourcemap。同样寻找 declaration 和 declarationMap 的用例。

我已经在互联网上搜索过了,但是除了生成 .d.ts 文件之外,我找不到实际的用例。

生成 .d.ts 文件正是 declaration 编译器选项的用例,因此构建输出为 .js,而所有类型定义仍可保留以供其他 TS 项目使用你的项目。

IDE可以利用declarationMap option to provide better developer experience: It enables you to quickly navigate to the original sources, when you currently have a corresponding .d.ts file open and want to see its implementation (see also ).

Enabling --declarationMap alongside --declaration causes the compiler to emit .d.ts.map files alongside the output .d.ts files. Language Services can also now understand these map files, and uses them to map declaration-file based definition locations to their original source, when available.

In other words, hitting go-to-definition on a declaration from a .d.ts file generated with --declarationMap will take you to the source file (.ts) location where that declaration was defined, and not to the .d.ts.

随着应用程序的增长,Typescript 对代码进行类型检查和编译的时间会越来越长。对于大型代码库,缓慢的编译时间会严重减慢您的开发速度。为了克服这个问题,从 Typescript 3.0 开始,你可以使用 Project References 将你的大项目拆分成更小的子项目。 declarationdeclarationMap 选项在这里起着重要作用。


declaration 选项

启用 declaration 选项将导致 Typescript 编译器创建声明文件 (.d.ts)。 .d.ts 文件包含相应 .ts 文件中使用的类型的声明。它们不包含类型的实现,它们只包含可公开访问的类型声明。

因此,任何人都可以在其他某个 Typescript 项目中使用您的 Typescript 项目中的类型。编译器可以在您的 .d.ts 文件的帮助下对其他项目中的代码进行类型检查,即使它们无权访问您的项目。

当您将一个大项目拆分为多个较小的子项目时,这会很有帮助。子项目可以访问彼此的声明文件。当您的一个子项目(比如 B)依赖于另一个子项目(比如 A)中声明的类型时,编译器使用子项目 A 中的 .d.ts 文件来类型检查和编译子项目项目 B 而无需再次编译子项目 A。这会缩短大型项目的编译时间。


declarationMap 选项

启用 declarationMap 选项时,Typescript 编译器会创建声明源映射 (.d.ts.map) 文件。声明源映射文件包含 link 在 .d.ts 文件中生成的每个类型声明回到原始源文件 (.ts) 的映射定义。这些文件中的映射定义采用 JSON 格式。

这些被您的 editor/IDE 使用。您将能够使用“转到定义”和“重命名”等编辑器功能来跨子项目导航和编辑代码。这意味着,例如,如果您在一个子项目中重命名一种类型,则更改也会传播到其他子项目。


请注意,即使您不拆分项目,也可以使用这些选项。如果您想让 .d.ts 文件的编辑器具有“转到定义”功能,这将很有用。如果您在 .d.ts 文件的声明中点击“转到定义”,您将被带到源文件 (.ts) 位置而不是 .d.ts 的位置。但这些选项在拆分项目中确实大放异彩。

就是这样!希望对您有所帮助。

如果您的项目包含超过 150 个文件,建议使用 Project References.

将其拆分为更小的子项目