将 Babel 与 TypeScript 结合使用

用于 TypeScript 的 Babel 与 tsc

¥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

    ¥Is your build output mostly the same as your source input files? Use tsc

  • 你是否需要具有多个潜在输出的构建管道?使用 babel 进行转译,使用 tsc 进行类型检查

    ¥Do you need a build pipeline with multiple potential outputs? Use babel for transpiling and tsc for type checking

用于转译的 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: