rollup-plugin-esbuild 使用教程
项目介绍
rollup-plugin-esbuild
是一个 Rollup 插件,它结合了 ESBuild 和 Rollup 来转换 ESNext 和 TypeScript 代码。这个插件旨在提供迄今为止最快的 TypeScript/ESNext 编译器和压缩器之一。它可以替换 rollup-plugin-typescript2
、@rollup/plugin-typescript
和 rollup-plugin-terser
等插件。
项目快速启动
安装
首先,你需要安装 rollup-plugin-esbuild
:
npm install -D rollup-plugin-esbuild esbuild
配置 Rollup
在你的 rollup.config.js
文件中,引入并配置 rollup-plugin-esbuild
:
import esbuild from 'rollup-plugin-esbuild';
export default {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs',
},
plugins: [
esbuild({
// 所有选项都是可选的
include: /\.tsx?$/,
}),
],
};
运行 Rollup
运行 Rollup 进行打包:
npx rollup -c
应用案例和最佳实践
案例一:多入口构建
如果你的项目有多个入口文件,可以配置 Rollup 支持多入口构建:
export default {
input: ['src/index.ts', 'src/utils.ts'],
output: {
dir: 'dist',
format: 'es',
},
plugins: [
esbuild({
include: /\.tsx?$/,
}),
],
};
案例二:代码压缩
通过配置 esbuild
插件的 minify
选项,可以实现代码压缩:
esbuild({
include: /\.tsx?$/,
minify: true,
}),
典型生态项目
生态项目一:rollup-plugin-eslint
rollup-plugin-eslint
是一个用于 Rollup 的 ESLint 插件,可以帮助你在构建过程中进行代码检查:
npm install -D @rbnlffl/rollup-plugin-eslint
在 rollup.config.js
中配置:
import eslint from '@rbnlffl/rollup-plugin-eslint';
export default {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs',
},
plugins: [
eslint(),
esbuild({
include: /\.tsx?$/,
}),
],
};
生态项目二:rollup-plugin-swc
rollup-plugin-swc
是一个使用 SWC 编译捆绑包的 Rollup 插件:
npm install -D rollup-plugin-swc
在 rollup.config.js
中配置:
import swc from 'rollup-plugin-swc';
export default {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs',
},
plugins: [
swc({
jsc: {
parser: {
syntax: 'typescript',
},
target: 'es2018',
},
}),
],
};
通过这些配置,你可以充分利用 rollup-plugin-esbuild
及其生态项目来优化你的前端构建流程。