Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsc/babel 编译 ts 的选择 #38

Open
nmsn opened this issue Aug 26, 2022 · 1 comment
Open

tsc/babel 编译 ts 的选择 #38

nmsn opened this issue Aug 26, 2022 · 1 comment

Comments

@nmsn
Copy link
Owner

nmsn commented Aug 26, 2022

如题

@nmsn
Copy link
Owner Author

nmsn commented Apr 10, 2023

原文:https://mp.weixin.qq.com/s/N5xVhQzBDy-Dj2ccFVru6Q

特点

babel

  • 编译针对单文件,无法做类型检查(直接去掉类型信息)
  • 语法支持不完全
    • 不支持 const enum,会当作 enum 处理,因为 babel 只是针对单文件处理

    • namespace 部分支持。不支持 namspace 的跨文件合并

    • babel 不会生成声明文件(babel 只负责把 TS 语法转换成 JS(其实就是去掉 TS 那些类型标记和声明),然后再转译 JS 成低版本,不会生成声明文件)

      tsc --emitDeclarationOnly 

      单独生成声明文件

tsc

  • 编译过程解析多文件,能够做类型的引入、多个文件的 namespace、enum、interface 等的合并,因此能够进行类型检查
  • 不支持还在草案阶段的语法

babel 编译的优势

产物体积更小

tsc 如果要支持 polyfill 的语法,只能手动引入 core-js;

babel 有相关的配置,而且可以选择按需加载 useBuiltIns: 'usage'

还可以通过 @babel/plugin-transform-runtime 来把全局的 corejs 的 import 转成模块化引入的方式

支持更新的语法

typescript 默认支持很多 es 的特性,但是不支持还在草案阶段的特性,babel 的 preset-env 支持所有标准特性,还可以通过 proposal 来支持更多还未进入标准的特性。

编译速度

tsc 会在编译过程中进行类型检查,类型检查需要综合多个文件的类型信息,要对 AST 做类型推导,比较耗时,而 babel 不做类型检查,所以编译速度会快很多。

推荐用法

  • babel 编译
  • tsc 做类型检查和生成声明文件
{
    "scripts": {
        "typeCheck": "tsc --noEmit",
        "buildTsDe" "tsc --emitDeclarationOnly",
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant