所以也许我很困惑,但我认为如果我将 declaration:true
添加到我的 tsconfig.json 我可以让它 tsc 复制我的 *.d.ts
文件,连同转译后的代码 & 它是 d.ts
文件?
如:
- 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
。具体工具取决于您的项目和构建类型、操作系统等。此工具在将文件复制到 build
时应保留 src
下的目录结构,以便 import
类型引用仍然有效。仅举几例:cp --parents
(shell)、rsync
、robocopy
或独立于平台的 npm 包,如 copyfiles :
"scripts": {
"copy-dts": "copyfiles -u 1 \"src/**/*.d.ts\" build"
}
解决方案 #2:将 d.ts 文件改写为 .ts 扩展名
将您的 .d.ts
文件改写为 .ts
扩展名(或将类型重新整合到现有的 .ts
文件中),因此tsc
负责在输出中发出声明。轻微的缺点:您没有编译器在类型和实现代码之间强制分离(d.ts
文件不允许包含代码)。最大的优势是,您不需要额外的构建步骤。
在我看来,后者是生成公共(public) API 的最简单方法,例如对于你的 npm 包,而 .d.ts
文件可以成为内部使用和共享类型声明的候选者。
关于Typescript 不会复制 d.ts 文件来构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018167/