最完整前端Rollup打包实战:从入门到架构优化
前言:为什么选择Rollup?
你还在为Webpack配置复杂而头疼?还在为Vite生产环境打包体积过大而困扰?本文将带你掌握Rollup(Rollup.js,一款JavaScript模块打包器)的全方位实战技能,从基础配置到高级优化,让你轻松构建高性能前端项目。
读完本文你将获得:
- 掌握Rollup核心配置与插件系统
- 实现TypeScript/PostCSS等现代前端技术栈集成
- 学会代码分割、懒加载等性能优化手段
- 解决10+常见打包问题的方案
- 一套可直接复用的企业级配置模板
Rollup vs Webpack vs Vite:全方位对比
| 特性 | Rollup | Webpack | Vite |
|---|---|---|---|
| 核心优势 | Tree-shaking极致优化 | 生态完善、插件丰富 | 开发启动快、热更新快 |
| 包体积 | 极小 | 较大 | 中等 |
| 配置复杂度 | 中等 | 高 | 低 |
| 适用场景 | 类库开发、小型应用 | 大型应用、复杂依赖 | 中大型应用、快速原型 |
| 学习曲线 | 平缓 | 陡峭 | 平缓 |
| 社区活跃度 | 中等 | 高 | 高 |
环境准备与基础安装
安装Rollup
# 全局安装
npm install rollup --global
# 项目本地安装(推荐)
mkdir rollup-demo && cd rollup-demo
npm init -y
npm install rollup --save-dev
国内CDN资源配置
推荐使用BootCDN提供的Rollup资源:
<script src="https://cdn.bootcdn.net/ajax/libs/rollup/4.49.0/rollup.browser.min.js"></script>
基础配置:从0构建第一个项目
项目结构设计
rollup-demo/
├── src/
│ ├── main.js # 入口文件
│ ├── utils/
│ │ └── math.js # 工具模块
│ └── components/
│ └── button.js # 组件模块
├── rollup.config.mjs # Rollup配置文件
└── package.json # 项目配置
核心代码实现
src/utils/math.js
// 加法函数
export const add = (a, b) => a + b;
// 乘法函数
export const multiply = (a, b) => a * b;
src/components/button.js
export default function createButton(text) {
const button = document.createElement('button');
button.textContent = text;
button.className = 'custom-button';
return button;
}
src/main.js
import { add } from './utils/math.js';
import createButton from './components/button.js';
// 创建按钮
const button = createButton('计算 2+3');
button.addEventListener('click', () => {
alert(`2 + 3 = ${add(2, 3)}`);
});
document.body.appendChild(button);
基础配置文件
rollup.config.mjs
export default {
input: 'src/main.js', // 入口文件
output: {
file: 'dist/bundle.js', // 输出文件
format: 'iife', // 输出格式:立即执行函数
name: 'RollupDemo' // 全局变量名称
}
};
运行与打包
package.json
{
"scripts": {
"build": "rollup -c",
"watch": "rollup -c -w"
}
}
执行打包命令:
npm run build
插件系统:扩展Rollup能力
必备核心插件
| 插件名称 | 作用 | 安装命令 |
|---|---|---|
| @rollup/plugin-node-resolve | 解析node_modules模块 | npm i @rollup/plugin-node-resolve -D |
| @rollup/plugin-commonjs | 转换CommonJS为ES模块 | npm i @rollup/plugin-commonjs -D |
| @rollup/plugin-json | 导入JSON文件 | npm i @rollup/plugin-json -D |
| @rollup/plugin-terser | 代码压缩 | npm i @rollup/plugin-terser -D |
| @rollup/plugin-babel | Babel转译 | npm i @rollup/plugin-babel @babel/core @babel/preset-env -D |
JSON文件导入配置
rollup.config.mjs
import json from '@rollup/plugin-json';
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'iife',
name: 'RollupDemo'
},
plugins: [
json({
compact: true, // 紧凑输出
namedExports: true // 支持命名导出
})
]
};
使用JSON导入:
// src/main.js
import { version } from '../package.json';
console.log(`当前版本: v${version}`);
代码压缩与优化
rollup.config.mjs
import terser from '@rollup/plugin-terser';
export default {
// ...其他配置
plugins: [
// ...其他插件
terser({
compress: {
drop_console: true, // 移除console
drop_debugger: true // 移除debugger
},
format: {
comments: false // 移除注释
}
})
]
};
高级配置:TypeScript与CSS集成
TypeScript集成
- 安装依赖:
npm install @rollup/plugin-typescript typescript tslib -D
- 创建TypeScript配置文件tsconfig.json:
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
- 配置Rollup:
import typescript from '@rollup/plugin-typescript';
export default {
// ...其他配置
plugins: [
// ...其他插件
typescript({
tsconfig: './tsconfig.json',
outputToFilesystem: true
})
]
};
CSS处理方案
- 安装依赖:
npm install rollup-plugin-postcss postcss autoprefixer cssnano -D
- 配置PostCSS:
import postcss from 'rollup-plugin-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
export default {
// ...其他配置
plugins: [
// ...其他插件
postcss({
plugins: [
autoprefixer(), // 自动添加前缀
cssnano() // CSS压缩
],
extract: 'css/bundle.css', // 提取CSS到单独文件
modules: false, // 禁用CSS Modules
minimize: true // 开启压缩
})
]
};
代码分割与懒加载
动态导入实现懒加载
// src/main.js
document.getElementById('loadModule').addEventListener('click', async () => {
const module = await import('./utils/lazyModule.js');
module.default();
});
多入口配置与代码分割
rollup.config.mjs
export default {
input: {
main: 'src/main.js',
admin: 'src/admin.js'
},
output: {
dir: 'dist', // 输出目录
format: 'es', // ES模块格式
entryFileNames: '[name].js', // 入口文件命名
chunkFileNames: 'chunks/[name]-[hash].js' // chunk文件命名
},
plugins: [/* ...插件 */]
};
开发环境配置
开发服务器与热更新
npm install rollup-plugin-serve rollup-plugin-livereload -D
rollup.config.mjs
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
export default {
// ...其他配置
plugins: [
// ...其他插件
process.env.NODE_ENV === 'development' && serve({
open: true, // 自动打开浏览器
contentBase: 'dist', // 服务根目录
port: 8080 // 端口号
}),
process.env.NODE_ENV === 'development' && livereload('dist') // 监听dist目录
]
};
package.json
{
"scripts": {
"dev": "NODE_ENV=development rollup -c -w",
"build": "NODE_ENV=production rollup -c"
}
}
生产环境优化
缓存配置提升构建速度
// rollup.config.mjs
let cache;
export default {
// ...其他配置
cache, // 缓存配置
plugins: [/* ...插件 */]
};
// 在构建脚本中保存缓存
async function build() {
const bundle = await rollup.rollup(config);
cache = bundle.cache;
await bundle.write(config.output);
}
环境变量注入
npm install @rollup/plugin-replace -D
rollup.config.mjs
import replace from '@rollup/plugin-replace';
export default {
// ...其他配置
plugins: [
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
__VERSION__: JSON.stringify('1.0.0')
})
]
};
常见问题与解决方案
1. 第三方库引入问题
问题:某些第三方库使用CommonJS模块格式,导致Rollup无法正确解析。
解决方案:使用@rollup/plugin-commonjs插件,并配置include选项:
import commonjs from '@rollup/plugin-commonjs';
export default {
// ...其他配置
plugins: [
commonjs({
include: /node_modules/ // 只处理node_modules中的文件
})
]
};
2. 循环依赖处理
问题:ES模块循环依赖导致运行时错误。
解决方案:
export default {
// ...其他配置
treeshake: {
moduleSideEffects: 'no-external', // 外部模块无副作用
propertyReadSideEffects: false // 属性读取无副作用
}
};
3. 全局变量访问
问题:需要访问window等全局变量。
解决方案:
export default {
// ...其他配置
context: 'window', // 设置全局上下文
output: {
// ...其他配置
globals: {
jquery: '$' // 外部依赖映射到全局变量
}
}
};
企业级配置模板
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import terser from '@rollup/plugin-terser';
import babel from '@rollup/plugin-babel';
import typescript from '@rollup/plugin-typescript';
import postcss from 'rollup-plugin-postcss';
import replace from '@rollup/plugin-replace';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
const isDev = process.env.NODE_ENV === 'development';
export default {
input: 'src/main.ts',
output: {
dir: 'dist',
format: isDev ? 'es' : 'iife',
name: 'App',
sourcemap: isDev,
entryFileNames: isDev ? '[name].js' : '[name].[hash].js',
chunkFileNames: isDev ? 'chunks/[name].js' : 'chunks/[name].[hash].js',
assetFileNames: isDev ? '[name].[ext]' : '[name].[hash].[ext]'
},
plugins: [
resolve({
browser: true,
preferBuiltins: false
}),
commonjs({
include: /node_modules/
}),
json(),
typescript({
tsconfig: './tsconfig.json'
}),
babel({
babelHelpers: 'runtime',
exclude: /node_modules/,
presets: ['@babel/preset-env']
}),
postcss({
plugins: [
autoprefixer(),
cssnano()
],
extract: true,
minimize: !isDev
}),
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
!isDev && terser(),
isDev && serve({
open: true,
contentBase: 'dist',
port: 8080
}),
isDev && livereload('dist')
],
external: ['react', 'react-dom'] // 外部依赖
};
总结与展望
通过本文的学习,你已经掌握了Rollup从基础到高级的全方位应用技能,包括核心配置、插件系统、TypeScript集成、代码分割、性能优化等关键知识点。Rollup作为一款专注于ES模块的打包工具,在类库开发和追求极致包体积的项目中具有显著优势。
未来Rollup将继续与Vite等构建工具深度融合,在保持精简核心的同时,进一步提升构建性能和开发体验。建议关注Rollup官方文档和插件生态,持续优化你的项目构建流程。
收藏与关注
如果本文对你有帮助,请点赞👍收藏🌟关注三连,下一期将带来《Vite+Rollup架构深度优化实战》。
附录:常用命令参考
| 命令 | 作用 |
|---|---|
| rollup -c | 使用配置文件打包 |
| rollup -w | 监听文件变化 |
| rollup -i src/main.js -o dist/bundle.js -f iife | 简单打包 |
| NODE_ENV=production rollup -c | 生产环境打包 |
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



