进阶 unplugin.unjs.io 2026-10-08 10:00:35 · 6 阅读

第6章 unplugin-swc:多框架通用 SWC 插件使用指南

unplugin-swc

适用于 Vite、Rollup 和 Webpack 的 SWC 插件。

安装

bash npm i unplugin-swc @swc/core -D

使用

Vite、Rollup 或 Webpack:

ts import swc from 'unplugin-swc'

export default { plugins: [ // Vite 插件 swc.vite(), // Rollup 插件 swc.rollup(), // Webpack 插件 swc.webpack(), ], }

tsconfig.json

以下 SWC 选项会自动从 tsconfig.json 中推断:

- jsc.parser.syntax:根据文件扩展名确定 - jsc.parser.jsx、parser.tsx:来自 compilerOptions.jsx - jsc.parser.decorators:来自 compilerOptions.experimentalDecorators - jsc.transform.react.pragma:来自 compilerOptions.jsxFactory - jsc.transform.react.pragmaFrag:来自 compilerOptions.jsxFragmentFactory - jsc.transform.react.importSource:来自 compilerOptions.jsxImportSource - jsc.transform.react.runtime:当 compilerOptions.jsx 为 "react-jsx" 或 "react-jsxdev" 时为 automatic,否则为 classic - jsc.transform.react.development:当 compilerOptions.jsx 为 "react-jsxdev" 时启用 - jsc.transform.legacyDecorator:来自 compilerOptions.experimentalDecorators - jsc.transform.decoratorMetadata:来自 compilerOptions.emitDecoratorMetadata - jsc.keepClassNames:启用装饰器时自动设置,因为 type-graphql 等库需要原始类名来生成正确的 graphql 类型

如果想关闭这个行为,改用 .swcrc 来控制上述 jsc 选项,可以使用 tsconfigFile 选项:

ts // 或 swc.rollup swc.vite({ tsconfigFile: false, })

// 也可以指定自定义的 tsconfig 文件,而不使用 tsconfig.json swc.vite({ tsconfigFile: './tsconfig.build.json', })

代码压缩

使用 minify: true 选项。该选项仅对 Rollup 有效:Vite 使用 esbuild 压缩代码,Webpack 的压缩则不支持。

如果需要对压缩过程做更精细的控制,请在 .swcrc 中使用 jsc.minify 选项。

Vite

使用该插件时,esbuild 会被自动禁用。

选项

该插件接受所有 @swc/core 选项(其中 jsc 应改为在 .swcrc 中配置),此外还有一些插件特有的选项:

options.tsconfigFile

类型:boolean, string

默认值:tsconfig.json

禁用 tsconfig 文件,或指定自定义的 tsconfig 文件。

options.include

类型:RegExp

默认值:/\.[jt]sx?$/

需要参与转译的文件。

options.exclude

类型:RegExp

默认值:/node_modules/

需要排除在转译之外的文件。

options.jsc

类型:object

要与默认配置合并的自定义 jsc 选项。

License

MIT © EGOIST

评论 (0)