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

标签 typescript typescript-typings .d.ts

所以也许我很困惑,但我认为如果我将 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)、rsyncrobocopy 或独立于平台的 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/

相关文章:

angular - 如何访问效果中的状态树? (@ngrx/效果 2.x)

Javascript 重载函数由 Visual Studio 代码智能感知检测

javascript - 为什么在推送更改检测时属性更改仍然导致 @Input 在 ngDoCheck 中发生更改?

typescript :如何为返回文字对象的工厂函数定义类型

javascript - 对象类型在确定类型文件中的应用

typescript - 如何使用 nestjs 处理 Mongoose 错误

reactjs - 在带有 React 和 Typescript 的 div 上使用 onFocus

TypeScript:从其他字符串文字联合类型限制区分联合中的鉴别器

javascript - 如何在没有引用路径的 angularjs 应用程序中使用 typescript 定义文件 (.d.ts)?

javascript - 类型定义文件