Typescript 不会复制 d.ts 个文件来构建

Typescript does not copy d.ts files to build

所以也许我很困惑,但我认为如果我将 declaration:true 添加到我的 tsconfig.json 我可以让它 tsc 复制我的 *.d.ts 文件,连同转译的代码是 d.ts 个文件?

EG:

- src
 - lib
   - types.d.ts
   - foo.ts

我希望 tsc 的结果类似于:

- build
 - lib
   - types.d.ts
   - foo.js
   - foo.d.ts

但是,我似乎无法将 types.d.ts 复制到我的构建目录。

typescript 不提供任何机制来复制 .d.ts 文件吗?或者我只是在某处配置错误? (此时我已经尝试了很多不同的配置;似乎没有任何效果)

你是对的 - declaration:true 意味着只有每个给定的 .ts 文件 tsc 生成并复制相应的 .d.ts 输出文件到 build目录(除了 .js.map 如果适用)。因此 tsc 不会将您的自定义 types.d.ts 文件复制到输出目录。

基本上 .d.ts 文件被视为编译器进行类型检查的不可触及的输入。它们不用于任何输出生成,这也意味着它们不会被复制到 build。您可以阅读更多 here 维护者的观点:

The .d.ts files you use are an input to the build system but not an output. It's perfectly reasonable to consume some types from a .d.ts but have your output not use those types, so there'd be no reason to distribute the input .d.ts with your build results. [...] It sounds like you'll want a post-build step in your build tool to copy the relevant .d.ts files wherever you need them.

The .d.ts files are considered "references" the compiler will not touch them, not move them, or recreate them. An easy way to think of the .d.ts files is that they go along with your .js files. if you are copying the .js files, you should copy the matching .d.ts.

解决方案 #1:通过手动构建步骤复制 d.ts 文件

一个可能的解决方案是在构建步骤中手动复制所有需要的 .d.ts 文件,例如 types.d.ts。具体工具取决于您的项目和构建类型,OS 等。当将文件复制到 build 时,此工具应保留 src 下的目录结构,以便 import 类型引用仍然有效。仅举几例:cp --parents (shell), rsync, robocopy or a platform independent npm package like copyfiles:

"scripts": {
  "copy-dts": "copyfiles -u 1 \"src/**/*.d.ts\" build"
}

解决方案 #2:将 d.ts 文件改写为 .ts 扩展名

将您的 .d.ts 文件改写为 .ts 扩展名(或 re-integrate 类型为现有的 .ts 文件),因此 tsc 负责发出输出中的声明。轻微的缺点:你没有编译器在类型和实现代码之间强制分离(d.ts 文件不允许包含代码)。最大的优势是,您不需要额外的构建步骤。

在我看来,后者是生成 public API 的最简单方法,例如对于您的 npm 包,而 .d.ts 文件可以成为内部使用和共享类型声明的候选者。

希望对您有所帮助。