Перейти к содержимому

esbuild и SWC

esbuild — сверхбыстрый JavaScript/TypeScript bundler написанный на Go. В 10-100x быстрее webpack/rollup.

Используется внутри: Vite (dev transform), Remix, Parcel, SvelteKit.

  • Сборка утилит/библиотек без сложных трансформаций
  • Build scripts (замена webpack в Node.js скриптах)
  • Быстрый bundle для простых SPA
  • Transform TypeScript/JSX файлов как часть build pipeline
Окно терминала
# Установка
npm install -D esbuild
# Bundle одного файла
npx esbuild src/main.tsx --bundle --outfile=dist/bundle.js
# Production build (minify + tree-shaking)
npx esbuild src/main.tsx \
--bundle \
--minify \
--sourcemap \
--target=es2020 \
--outfile=dist/bundle.js
# Watch mode
npx esbuild src/main.tsx --bundle --watch --outfile=dist/bundle.js
build.ts
import * as esbuild from 'esbuild';
const result = await esbuild.build({
entryPoints: ['src/main.tsx'],
bundle: true,
outfile: 'dist/bundle.js',
platform: 'browser',
target: ['es2020', 'chrome90', 'firefox88'],
format: 'esm',
// CSS modules, images, etc.
loader: {
'.png': 'file',
'.svg': 'text',
'.css': 'css',
},
// Разделение на чанки
splitting: true,
format: 'esm',
outdir: 'dist', // splitting требует outdir, не outfile
// Внешние зависимости (не включать в bundle)
external: ['react', 'react-dom'],
// Заменить переменные
define: {
'process.env.NODE_ENV': '"production"',
__VERSION__: '"1.0.0"',
},
// Минификация
minify: true,
sourcemap: true,
metafile: true, // для анализа bundle
});
// Анализ размера bundle
const text = await esbuild.analyzeMetafile(result.metafile!);
console.log(text);
dev.ts
import * as esbuild from 'esbuild';
const ctx = await esbuild.context({
entryPoints: ['src/main.tsx'],
bundle: true,
outdir: 'dist',
sourcemap: true,
define: { 'process.env.NODE_ENV': '"development"' },
});
// Встроенный dev server
await ctx.serve({
servedir: 'dist',
port: 3000,
onRequest: ({ method, path, status, timeInMS }) => {
console.log(`${method} ${path}: ${status} [${timeInMS}ms]`);
},
});
await ctx.watch();
console.log('Watching...');

SWC (Speedy Web Compiler) — Rust-based компилятор TypeScript/JSX. Аналог Babel, но в 20x быстрее.

Используется внутри: Next.js (с версии 12), Parcel v2, Vite (через @vitejs/plugin-react-swc).

Окно терминала
npm create vite@latest my-app -- --template react-swc-ts
# Или для существующего проекта:
npm install -D @vitejs/plugin-react-swc
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc'; // SWC вместо Babel
export default defineConfig({
plugins: [react()],
});
КритерийBabelSWC
ЯзыкJavaScriptRust
Скорость1x20x+
Поддержка плагинов100% (огромная экосистема)Ограниченная
TypeScript strips
JSX трансформация
Decorators
Кастомные Babel плагины
Окно терминала
npm install -D @swc/core @swc/cli
// Программный API
import { transform } from '@swc/core';
const result = await transform(
`const x: number = 1;`, // TypeScript
{
jsc: {
parser: { syntax: 'typescript' },
target: 'es2020',
},
}
);
console.log(result.code); // 'const x = 1;'
// Трансформация JSX
const jsxResult = await transform(
`const el = <div>Hello</div>;`,
{
jsc: {
parser: { syntax: 'ecmascript', jsx: true },
transform: {
react: {
runtime: 'automatic', // React 17+ transform
},
},
},
}
);
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true
},
"transform": {
"react": {
"runtime": "automatic",
"development": false,
"refresh": false
},
"legacyDecorator": true,
"decoratorMetadata": true
},
"target": "es2020",
"loose": false,
"externalHelpers": false
},
"module": {
"type": "es6"
},
"sourceMaps": true
}
ИнструментUse case
ViteSPA/MPA разработка — лучший выбор для React+TypeScript
esbuildLibrary bundling, build scripts, нет сложных трансформаций
SWCУскорение существующего Babel pipeline или Vite с SWC плагином
WebpackLegacy проекты, нужна специфичная экосистема плагинов
RollupLibrary publishing (tree-shaking по умолчанию)