SWC 上手
Apr 05, 2024 ·
3 Min Read
文档
可扩展的基于 Rust 的平台,用于下一代快速开发工具。可用于编译和捆绑,对标 Babel。
现在 vite
也有使用 swc
的模板了,有兴趣的可以一试。但暂不支持 Vue
官方介绍 比 Babel 快 20倍。 🤩🤩🤩
@swc/cli
类似于@babel/cli
@swc/core
类似于@babel/core
安装
npm i -D @swc/cli @swc/core
转换
npx swc source.js -o dist.js
案例上手
{ "jsc": { "parser": { "syntax": "typescript", "tsx": true, }, "target": "es5", "loose": false, "minify": { "compress": false, "mangle": false, } }, "module": { "type": "umd", }, "minify": true, "isModule": true}
class Person { private name: string private age: number constructor(name: string, age: number) { this.name = name this.age = age }
sayHi() { console.log(`My name is ${this.name}, and I'm ${this.age} years old`) }}
const start = () => { const boy = new Person('kim', 18) boy.sayHi()}
export default start

你可以尝试切换不同的配置,查看一下输出的结果有什么不同!!!
配置文件解析
swc 的配置文件为 .swcrc
,使用 JSON 格式。
"jsc": { "parser": { // 解析器 "syntax": "typescript", // ecmascript | typescript,对应 js 和 ts "tsx": true, // 是否解析tsx,ecmascript 对应 jsx;对应插件 @babel/plugin-transform-react-jsx "decorators": false, // 是否支持装饰器,对应插件 @babel/plugin-syntax-decorators "dynamicImport": false // 是否支持动态导入,对应插件 @babel/plugin-syntax-dynamic-import }, "transform": null, "target": "es5", // 指定目标环境,即输出的js规范 "loose": false, // 松散模式,类似 babel-preset-env "externalHelpers": false, // 是否开启辅助函数,true 的时候以模块方式导入;babel也有类似的 helpers "keepClassNames": false, // 是否保留原始类名 "minify": { // 压缩相关 "compress": true, // 对应 terser 的压缩选项 "mangle": true, // 对应 terser 的处理选项 } }, "module": { "type": "umd", // 输出模块规范 "strict": false, // 用于防止__esModule属性 "strictMode": true, // 严格模式 "lazy": false, "noInterop": false }, "env": { // 浏览器兼容,类似 babel 中的 presets env "targets": { "chrome": "79" }, "coreJs": "3.29.1", // 使用的 corejs 版本 // "include": [], // 要包含的功能或模块 // "exclude": [], // 要排除的功能或模块 }, "minify": true, // 开启压缩 "isModule": true}
swc 还支持打包 👉🏻 swcpack,但不建议正式环境中使用,目前还处于开发中。
配合 webpack 使用
- 安装
swc-loader
npm i -D swc-loader
- 配置文件添加 loader
module.exports = { module: { rules: [ { test: /\.(t|j)sx*$/, exclude: /(node_modules)/, use: { loader: "swc-loader" } } ] }}
✅✅✅ 完成可以使用了。
Last edited Feb 15