将 Babel 与 TypeScript 结合使用

Babel 与 tsc 对比 TypeScript

🌐 Babel vs tsc for TypeScript

在制作现代 JavaScript 项目时,你可能会问自己将文件从 TypeScript 转换为 JavaScript 的正确方法是什么?

🌐 When making a modern JavaScript project, you might ask yourself what is the right way to convert files from TypeScript to JavaScript?

很多时候,答案是“视情况而定”或者“可能有人已经为你做了决定”,这取决于具体项目。如果你是在使用现有框架构建项目,比如 tsdxAngularNestJS 或者在 入门指南 中提到的任何框架,那么这个决定已经为你处理好了。

🌐 A lot of the time the answer is “it depends”, or “someone may have decided for you” depending on the project. If you are building your project with an existing framework like tsdx, Angular, NestJS or any framework mentioned in the Getting Started then this decision is handled for you.

然而,一个有用的启发式方法可能是:

🌐 However, a useful heuristic could be:

  • 你的构建输出大部分和你的源输入文件一样吗?使用 tsc
  • 你需要一个具有多种潜在输出的构建管道吗?使用 babel 进行转译,使用 tsc 进行类型检查

使用 Babel 进行转译,使用 tsc 定义类型

🌐 Babel for transpiling, tsc for types

这是具有现有构建基础设施的项目的常见模式,这些基础设施可能已从 JavaScript 代码库移植到 TypeScript。

🌐 This is a common pattern for projects with existing build infrastructure which may have been ported from a JavaScript codebase to TypeScript.

这种技术是一种混合方法,使用 Babel 的 preset-typescript 来生成你的 JS 文件,然后使用 TypeScript 进行类型检查和 .d.ts 文件生成。

🌐 This technique is a hybrid approach, using Babel’s preset-typescript to generate your JS files, and then using TypeScript to do type checking and .d.ts file generation.

通过使用 babel 对 TypeScript 的支持,你可以获得使用现有构建管道的能力,并且更有可能拥有更快的 JS 触发时间,因为 Babel 不会对你的代码进行类型检查。

🌐 By using babel’s support for TypeScript, you get the ability to work with existing build pipelines and are more likely to have a faster JS emit time because Babel does not type check your code.

类型检查和 d.ts 文件生成

🌐 Type Checking and d.ts file generation

使用 Babel 的缺点是,在从 TS 转换到 JS 的过程中,你无法进行类型检查。这可能意味着在编辑器中未发现的类型错误可能会悄悄地进入生产代码。

🌐 The downside to using babel is that you don’t get type checking during the transition from TS to JS. This can mean that type errors which you miss in your editor could sneak through into production code.

除此之外,Babel 无法为你的 TypeScript 创建 .d.ts 文件,如果你的项目是一个库,这可能会使项目的使用变得更加困难。

🌐 In addition to that, Babel cannot create .d.ts files for your TypeScript which can make it harder to work with your project if it is a library.

要解决这些问题,你可能需要设置一个命令来使用 TSC 对你的项目进行类型检查。这可能意味着将你的一些 Babel 配置复制到相应的 tsconfig.json 中,并确保启用了这些标志:

🌐 To fix these issues, you would probably want to set up a command to type check your project using TSC. This likely means duplicating some of your babel config into a corresponding tsconfig.json and ensuring these flags are enabled:

"compilerOptions": {
// Ensure that .d.ts files are created by tsc, but not .js files
"": true,
// Ensure that Babel can safely transpile files in the TypeScript project
}

有关这些标志的更多信息:

🌐 For more information on these flags: