Skip to content
博客
介绍 SWC 1.0

介绍 SWC 1.0

February 8th, 2019 by DongYoon Kang

SWC 是什么?

swc (opens in a new tab) (speedy web compiler) 是一个超快的 JavaScript 编译器。

SWC 能做什么?

它可以将 TypeScript / jsx / ECMAScript 2019 转译为浏览器兼容的 JavaScript。

// input.js
 
class Foo {
  set foo(v) {}
}
class Bar extends Foo {
  get bar1() {}
  async bar2() {}
}

SWC 有多快?

它在单核同步基准测试中比 babel 快 16 倍 - 20 倍。注意,实际性能差距更大,因为 swc 在 worker 线程中工作,而 babel 在事件循环线程中工作。

安装

你可以使用以下命令安装 swc

# if you use npm
npm i -D @swc/core
 
# if you use yarn
yarn add -D @swc/core

See Getting Started for more details.

SWC 1.0 包含什么?

swc 实现了几乎所有的 babel 插件。截至 1.0.0,swc 可以理解各种 ECMAScript 方言,并将其编译为 es5。

ECMAScript 2019 支持

.swcrc:

{
  "jsc": {
    "parser": {
      "syntax": "ecmascript"
    }
  }
}

React (with jsx)

.swcrc:

{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": true
    }
  }
}

TypeScript support

swc 还可以将 typescript / tsx 编译为 ECMAScript。注意,它目前不进行类型检查。类型检查在 #126 (opens in a new tab) 中跟踪。

.swcrc:

{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": false
    }
  }
}

更多详情请参阅 docs

各种转换

  • es3

    • member-expression-literals
    • property-literals
    • reserved-words
  • es2015

    • arrow-functions
    • block-scoped-functions
    • block-scoping
    • classes
    • computed-properties
    • destructuring
    • duplicate-keys
    • for-of
    • function-name
    • instanceof
    • literals
    • new-target
    • parameters
    • shorthand-properties
    • spread
    • sticky regex (y flag)
    • template-literals
    • typeof-symbol
  • es2016

    • exponentiation-operator
  • es2017

    • async-to-generator
  • es2018

    • object-rest-spread
  • react

    • jsx

从 Babel 迁移

@babel/core

运行 npm i --save-dev @swc/coreyarn add --dev @swc/core

swc 默认启用所有转换。因此,如果你只使用标准的 ECMAScript,你可以删除 .babelrc 并将其更改为 swc.transform()

更多详情请参阅 usage docsmigration docs

注意,swc 目前不支持自定义插件。

@babel/cli

运行 npm i --save-dev @swc/core @swc/cliyarn add --dev @swc/core @swc/cli 来安装。@swc/cli 的 CLI 接口几乎与 @babel/cli 的接口相同。因此,如果你使用标准的 ECMAScript,你可以将 npx babel 替换为 npx swc。如果出现错误,请 报告错误 (opens in a new tab)

更多详情请参阅 usage docsmigration docs。注意,swc 目前不支持自定义插件。