Rollup 打包工具
Rollup 的特点、使用方法和配置
问题
介绍一下 Rollup 打包工具。
解答
Rollup 是一个 JavaScript 模块打包器,专注于 ES Module 的打包,特别适合打包库和框架。
基本使用
安装:
npm install rollup -D
配置文件
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser';
export default {
// 入口文件
input: 'src/index.js',
// 输出配置,支持多种格式
output: [
{
file: 'dist/bundle.cjs.js',
format: 'cjs', // CommonJS 格式
},
{
file: 'dist/bundle.esm.js',
format: 'es', // ES Module 格式
},
{
file: 'dist/bundle.umd.js',
format: 'umd', // UMD 格式,支持浏览器和 Node
name: 'MyLibrary', // UMD 需要指定全局变量名
},
],
// 插件配置
plugins: [
resolve(), // 解析 node_modules 中的模块
commonjs(), // 将 CommonJS 转换为 ES Module
babel({
babelHelpers: 'bundled',
exclude: 'node_modules/**',
}),
terser(), // 压缩代码
],
// 外部依赖,不打包进 bundle
external: ['react', 'react-dom'],
};
示例代码
// src/utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// src/index.js
export { add, multiply } from './utils.js';
export const calculate = (a, b) => ({
sum: add(a, b),
product: multiply(a, b),
});
运行打包
# 使用配置文件
rollup -c
# 命令行直接打包
rollup src/index.js --file dist/bundle.js --format es
Tree Shaking 效果
// 源码
export const used = () => 'used';
export const unused = () => 'unused';
// 使用方
import { used } from './module';
console.log(used());
// 打包结果:unused 函数会被移除
const used = () => 'used';
console.log(used());
Rollup vs Webpack
| 特性 | Rollup | Webpack |
|---|---|---|
| 适用场景 | 库/框架 | 应用程序 |
| Tree Shaking | 原生支持,效果好 | 需要配置 |
| 代码分割 | 支持 | 更强大 |
| 输出体积 | 更小 | 相对较大 |
| 配置复杂度 | 简单 | 复杂 |
| HMR | 需要插件 | 原生支持 |
关键点
- ES Module 优先:Rollup 基于 ES Module 设计,Tree Shaking 效果优于 Webpack
- 适合打包库:输出代码干净,支持多种模块格式(ESM、CJS、UMD)
- 插件系统:通过插件扩展功能,如
@rollup/plugin-node-resolve、@rollup/plugin-commonjs - 不适合复杂应用:缺少 HMR、代码分割等应用开发常用功能
- Vite 的基础:Vite 生产环境打包使用 Rollup
目录