Compile TS: ts-loader vs plugin-transform-typescript
Created by Qiwei on 5/9/2022 · Edited on 1/7/2024
开源中遇到一个 2020 年提出的 issue,项目中使用了
create-react-app,它的react-scripts编译 TypeScript 使用的是@babel/plugin-transform-typescript,它有一些缺点,比如不支持加载 TypeScript 运行时代码以缩小打包体积或支持更多原生 TS 特性,例如 tslib 和 const enum,也不能忠实还原 tsconfig.json 的每个配置。这些问题 现在 2022 还存在吗?存在的话怎么解决这些问题呢?
@babel/plugin-transform-typescript 的缺陷
经过一番调查,其实 babel 的文档中已经列出了他的 caveats。目前的版本(7.16)主要有 5 点:
- 没有类型检查
- 不支持
export =和import = tsconfig.json的修改没有反映在 babel 中- 不允许 export of a var or let
- 只有部分 TypeScript 的
namespace支持
可以看出, issue 中提到的“不能忠实还原 tsconfig.json” 这一点目前还是存在的。但是 ”不支持加载 tslib 和 const enum“ 目前已经没有这些问题。在 TypeScript Compiler Options 中,有写到
--importHelpers This is the equivalent of the @babel/plugin-transform-runtime package
所以 tslib 中的很多 helper 在 plugin-transform-typescript 应该也可以通过配置加载的。关于 const enum 的问题,在 7.15 后也有所优化(optimizeConstEnums)。
@babel/plugin-transform-typescript vs ts-loader
前面的这些信息还不足以让我决定使用哪个工具来编译使用 TS 的项目。
这里再做一些对比,比较 @babel/plugin-transform-typescript 和 ts-loader 这种使用 tsc 的工具有哪些不同点。
1. Babel 没有类型检查
Babel 不会管代码中的 TypeScript 类型,不会检查类型对不对。但是既然我们选择用 TypeScript,肯定或多或少想要类型检查的,不过这也不是个大问题,可以用 tsc --noEmit 来做类型检查,并且不做编译。同时,我们在写代码和看源码时需要类型的话,在 IDE 中使用 TypeScript 插件就够了。
2. decorator 和 metadata,tsc 有更好的支持
目前 ECMAScript 和 TypeScript 对于 Decorators 的行为和实现有出入。Babel 用的是 ECMAScript 的标准,所以 TypeScript 和 Babel 的输出会不一样。
但是 Babel 现在也允许我们选择使用 TypeScript 版的标准:
// 只用添加 @babel/plugin-proposal-decorators,设置 legacy 为 true
module.exports = {
plugins: [["@babel/plugin-proposal-decorators", { legacy: true }]],
};还有一个 TypeScript 才有的配置: emitDecoratorMetadata,通常 TypeScript 的输出在运行时不会有类型信息,但是这个 compiler option 可以让我们保留有 Decorator 的 class 和 methods 的类型,这个功能在 TypeORM、TypeGoose 等工具中用到,因为可以让他们做依赖注入和类型映射。
不过 Babel 目前也可以做到了,但是需要添加 babel-plugin-transform-typescript-metadata。
3. Babel 支持自定义 Transform
Babel 相比于 tsc 的一大优势是它可以支持自定义的 transform,比如你可以 写个插件做你需要的代码转换。TypeScript 虽然有 Transform API,但是 Babel 的相关生态要好很多。
不过你也可以把 tsc 的输出给 Babel,让它做你想要的转换。
4. 性能平手
Babel 直接扔掉类型的代码,也不用做检查,这样性能上会快一点点,但是总体上也没有快多少,而且大家通常会用 tsc --noEmit 来做类型检查。
关于打包的体积,没有看到太多的 benchmark 对比,但是应该是差不多的。
怎样选择?
看 TypeScript 官方的建议
A useful heuristic could be:
- Is your build output mostly the same as your source input files? Use tsc
- Do you need a build pipeline with multiple potential outputs? Use babel for transpiling and tsc for type checking
对于一个新的 TS 项目,我可能会选择 ts-loader,因为看起来支持更全面一些,如果需要 Babel 也可以把它的 output 传给 Babel。
对于已有的项目,比如最开始提到的这个开源项目,由于它的需求 babel 基本已实现,我准备继续使用 Babel plugin。