SWC 工具集成 #

集成概述 #

SWC 可以与多种工具和框架集成,提供快速的编译和打包能力:

text
┌─────────────────────────────────────────────────────────────┐
│                   SWC 集成生态                               │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  框架集成                                                    │
│  ├── Next.js(内置)                                         │
│  ├── Vite(插件)                                            │
│  ├── Nuxt.js(模块)                                         │
│  └── Remix(插件)                                           │
│                                                              │
│  打包工具                                                    │
│  ├── Webpack(loader)                                       │
│  ├── Rollup(插件)                                          │
│  ├── Parcel(内置)                                          │
│  └── esbuild(插件)                                         │
│                                                              │
│  测试工具                                                    │
│  ├── Jest(转换器)                                          │
│  ├── Vitest(内置)                                          │
│  └── Mocha(编译器)                                         │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Next.js 集成 #

自动集成 #

Next.js 12+ 默认使用 SWC 作为编译器:

javascript
// next.config.js
module.exports = {
  // 默认已启用 SWC
  swcMinify: true,
};

自定义 SWC 配置 #

javascript
// next.config.js
module.exports = {
  swcMinify: true,
  compiler: {
    // 启用装饰器
    decorators: true,
    // 启用 styled-components
    styledComponents: true,
    // 移除 console
    removeConsole: {
      exclude: ['error', 'warn'],
    },
    // React Remove Properties
    reactRemoveProperties: true,
    // Relay
    relay: {
      src: './src',
      artifactDirectory: './src/__generated__',
    },
  },
};

实验性功能 #

javascript
// next.config.js
module.exports = {
  experimental: {
    // 启用 SWC 插件
    swcPlugins: [
      [
        'swc-plugin-my-plugin',
        {
          option: 'value',
        },
      ],
    ],
  },
};

Vite 集成 #

安装插件 #

bash
npm install --save-dev @vitejs/plugin-react-swc

配置 Vite #

javascript
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
  plugins: [
    react({
      // JSX 配置
      jsxImportSource: 'react',
      // 使用 TSX
      tsDecorators: true,
    }),
  ],
});

自定义 SWC 配置 #

javascript
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
      plugins: [
        ['@swc/plugin-emotion', {}],
      ],
    }),
  ],
});

使用 .swcrc #

json
// .swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "tsx": true,
      "decorators": true
    },
    "transform": {
      "react": {
        "runtime": "automatic",
        "importSource": "react"
      }
    },
    "target": "es2020"
  }
}

Webpack 集成 #

安装 loader #

bash
npm install --save-dev swc-loader @swc/core

基本配置 #

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'swc-loader',
          options: {
            jsc: {
              parser: {
                syntax: 'ecmascript',
                jsx: true,
              },
              target: 'es2015',
            },
          },
        },
      },
    ],
  },
};

TypeScript 支持 #

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'swc-loader',
          options: {
            jsc: {
              parser: {
                syntax: 'typescript',
                tsx: true,
                decorators: true,
              },
              target: 'es2015',
            },
          },
        },
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
};

与 Babel 共存 #

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'swc-loader',
            options: {
              jsc: {
                parser: {
                  syntax: 'ecmascript',
                  jsx: true,
                },
                target: 'es2015',
              },
            },
          },
          // Babel 处理 SWC 不支持的特性
          {
            loader: 'babel-loader',
            options: {
              plugins: ['unsupported-plugin'],
            },
          },
        ],
      },
    ],
  },
};

Rollup 集成 #

安装插件 #

bash
npm install --save-dev @rollup/plugin-swc

基本配置 #

javascript
// rollup.config.js
import { swc } from '@rollup/plugin-swc';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
  },
  plugins: [
    swc({
      jsc: {
        parser: {
          syntax: 'ecmascript',
          jsx: true,
        },
        target: 'es2015',
      },
    }),
  ],
};

TypeScript 项目 #

javascript
// rollup.config.js
import { swc } from '@rollup/plugin-swc';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    swc({
      jsc: {
        parser: {
          syntax: 'typescript',
          tsx: true,
        },
        target: 'es2015',
      },
    }),
  ],
};

Jest 集成 #

安装依赖 #

bash
npm install --save-dev @swc/jest @swc/core

配置 Jest #

javascript
// jest.config.js
module.exports = {
  transform: {
    '^.+\\.(t|j)sx?$': '@swc/jest',
  },
};

自定义 SWC 配置 #

javascript
// jest.config.js
module.exports = {
  transform: {
    '^.+\\.(t|j)sx?$': [
      '@swc/jest',
      {
        jsc: {
          parser: {
            syntax: 'typescript',
            tsx: true,
            decorators: true,
          },
          transform: {
            react: {
              runtime: 'automatic',
            },
          },
          target: 'es2015',
        },
        module: {
          type: 'commonjs',
        },
      },
    ],
  },
};

使用 .swcrc #

javascript
// jest.config.js
module.exports = {
  transform: {
    '^.+\\.(t|j)sx?$': [
      '@swc/jest',
      {
        configFile: './.swcrc',
      },
    ],
  },
};

Vitest 集成 #

Vitest 默认使用 esbuild,可以切换到 SWC:

javascript
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
  plugins: [react()],
  test: {
    // Vitest 会使用 Vite 的 SWC 配置
    globals: true,
    environment: 'jsdom',
  },
});

Babel 集成 #

安装预设 #

bash
npm install --save-dev @swc/register

使用 @swc/register #

javascript
// 在入口文件顶部添加
require('@swc/register');

// 然后可以加载 TypeScript 文件
require('./src/index.ts');

使用 @swc/node #

bash
npm install --save-dev @swc/node
bash
# 运行 TypeScript 文件
swc-node src/index.ts

配置 #

javascript
// .swcrc
{
  "jsc": {
    "parser": {
      "syntax": "typescript"
    },
    "target": "es2015"
  },
  "module": {
    "type": "commonjs"
  }
}

ESLint 集成 #

使用 @typescript-eslint #

javascript
// .eslintrc.js
module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
};

配合 SWC #

bash
# SWC 负责编译,ESLint 负责检查
npm run lint    # ESLint 检查
npm run build   # SWC 编译

Prettier 集成 #

SWC 和 Prettier 可以配合使用:

json
// package.json
{
  "scripts": {
    "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
    "build": "swc src -d dist"
  }
}
javascript
// .prettierrc
module.exports = {
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: 'es5',
};

Turbopack 集成 #

Turbopack 是基于 SWC 的新一代打包器:

javascript
// next.config.js
module.exports = {
  experimental: {
    // 启用 Turbopack(开发模式)
    turbo: {
      resolveExtensions: ['.tsx', '.ts', '.jsx', '.js', '.json'],
    },
  },
};
bash
# 使用 Turbopack 运行开发服务器
next dev --turbo

Parcel 集成 #

Parcel 2 内置使用 SWC:

json
// .parcelrc
{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.{js,mjs,jsx}": ["@parcel/transformer-js"],
    "*.{ts,tsx}": ["@parcel/transformer-typescript-tsc"]
  }
}

Node.js 集成 #

使用 @swc/core #

javascript
const swc = require('@swc/core');

async function compile(code) {
  const result = await swc.transform(code, {
    jsc: {
      parser: {
        syntax: 'typescript',
      },
      target: 'es2015',
    },
    module: {
      type: 'commonjs',
    },
  });
  
  return result.code;
}

// 编译并运行
const compiled = await compile(`
  const greet = (name: string) => \`Hello, \${name}!\`;
  console.log(greet('World'));
`);

eval(compiled);

Express 中间件 #

javascript
const express = require('express');
const swc = require('@swc/core');
const path = require('path');
const fs = require('fs');

const app = express();

app.get('/*.js', async (req, res) => {
  const filePath = path.join(__dirname, 'src', req.path);
  
  if (fs.existsSync(filePath)) {
    const code = fs.readFileSync(filePath, 'utf-8');
    
    const result = await swc.transform(code, {
      jsc: {
        parser: {
          syntax: 'ecmascript',
          jsx: true,
        },
        target: 'es2015',
      },
    });
    
    res.type('javascript').send(result.code);
  } else {
    res.status(404).send('Not found');
  }
});

app.listen(3000);

Gulp 集成 #

javascript
const gulp = require('gulp');
const swc = require('@swc/core');
const through = require('through2');

function compile() {
  return through.obj(async (file, encoding, callback) => {
    if (file.isBuffer() && /\.(js|jsx|ts|tsx)$/.test(file.path)) {
      const result = await swc.transform(file.contents.toString(), {
        jsc: {
          parser: {
            syntax: 'typescript',
            tsx: true,
          },
          target: 'es2015',
        },
      });
      
      file.contents = Buffer.from(result.code);
      file.extname = '.js';
    }
    
    callback(null, file);
  });
}

gulp.task('build', () => {
  return gulp.src('src/**/*.{js,jsx,ts,tsx}')
    .pipe(compile())
    .pipe(gulp.dest('dist'));
});

Grunt 集成 #

javascript
// Gruntfile.js
module.exports = function(grunt) {
  const swc = require('@swc/core');
  
  grunt.initConfig({
    swc: {
      options: {
        jsc: {
          parser: {
            syntax: 'typescript',
          },
          target: 'es2015',
        },
      },
      files: {
        expand: true,
        cwd: 'src/',
        src: ['**/*.ts'],
        dest: 'dist/',
        ext: '.js',
      },
    },
  });
  
  grunt.registerMultiTask('swc', async function() {
    const done = this.async();
    const options = this.options();
    
    for (const file of this.files) {
      const code = grunt.file.read(file.src[0]);
      const result = await swc.transform(code, options);
      grunt.file.write(file.dest, result.code);
    }
    
    done();
  });
  
  grunt.registerTask('default', ['swc']);
};

常见问题 #

问题一:与 Babel 插件不兼容 #

解决方案:使用 SWC 插件替代,或混合使用

javascript
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          {
            loader: 'swc-loader',
          },
          {
            loader: 'babel-loader',
            options: {
              plugins: ['babel-plugin-only-sw-cant-handle'],
            },
          },
        ],
      },
    ],
  },
};

问题二:装饰器不工作 #

解决方案

json
{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true
    },
    "transform": {
      "legacyDecorator": true
    }
  }
}

问题三:Source Map 不正确 #

解决方案

javascript
// 确保 Source Map 配置一致
{
  "sourceMaps": true,
  "jsc": {
    // ...
  }
}

下一步 #

现在你已经掌握了 SWC 与各种工具的集成方法,接下来学习 高级用法 了解更多高级技巧!

最后更新:2026-03-28