For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/configure/app/tools/swc.md.
  • 简体中文
  • tools.swc

    • 类型: Object | Function
    • 默认值: undefined

    介绍

    SWC (Speedy Web Compiler) 是基于 Rust 语言编写的高性能 JavaScript 和 TypeScript 转译和压缩工具。在 Polyfill 和语法降级方面可以和 Babel 提供一致的能力,并且性能比 Babel 高出一个数量级。

    Modern.js 提供了开箱即用的 SWC 插件,可以为你的 Web 应用提供语法降级、Polyfill 以及压缩,并且移植了一些额外常见的 Babel 插件。

    Tip

    在使用 Rspack 作为打包工具时,默认会使用 SWC 进行转译和压缩,因此你不需要再安装和配置 SWC 插件。

    在 Rspack 模式下使用

    通过 tools.swc 可以设置 Rspack builtin:swc-loader 的选项。

    import { defineConfig } from '@modern-js/app-tools';
    
    export default defineConfig({
      tools: {
        swc: {
          jsc: {
            externalHelpers: false,
          },
        },
      },
    });

    更多用法可参考 Rsbuild - tools.swc。

    注册 SWC 插件

    Modern.js 支持通过 tools.swc 注册 SWC 的 Wasm 插件,比如注册 @swc/plugin-styled-components:

    export default {
      tools: {
        swc: {
          jsc: {
            experimental: {
              plugins: [['@swc/plugin-styled-components', {}]],
            },
          },
        },
      },
    };

    需要注意的是,SWC 的插件仍然是一个实验性功能,目前 SWC 的 Wasm 插件是不向后兼容的,SWC 插件的版本与 Rspack 依赖的 swc_core 版本存在强耦合关系。

    这意味着,你需要选择和当前 swc_core 版本匹配的 SWC 插件,才能使它正常执行。如果你使用的 SWC 插件版本与 Rspack 依赖的 swc_core 版本不匹配,Rspack 在执行构建时会抛出如下错误:

    1: failed to run Wasm plugin transform. Please ensure the version of `swc_core`
       used by the plugin is compatible with the host runtime.

    如果你遇到了以上问题,通常可行的解决方法是将 Modern.js 和 SWC 插件都升级到最新版本。

    详情可参考 Rsbuild - SWC 插件版本。