JavaScript 模块打包工具,以高效、简洁和优化著称,特别适合库和框架的打包。利用 ES6 模块静态分析,通过 Tree Shaking 去除未使用代码,生成更小、更高效的打包文件。

安装

npm install -g rollup
# 或项目内
npm install --save-dev rollup

配置文件 rollup.config.js

import path from 'path';
 
export default {
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife',  // 可选: 'cjs', 'es', 'umd', 'iife'
    name: 'MyBundle',
  },
  plugins: [],
};

常用命令

rollup -c                                              # 使用配置文件打包
rollup src/main.js --file dist/bundle.js --format iife # 指定入口和输出
rollup src/main.js --file dist/bundle.cjs --format cjs  # CommonJS 格式
rollup src/main.js --file dist/bundle.esm.js --format es # ES Module 格式

输出格式

格式用途
esES Module(现代浏览器/Node ESM)
cjsCommonJS(Node.js require)
umd通用(支持 AMD/CJS/全局变量)
iife浏览器直接引入

工具边界

  • Rollup 是库打包的首选,Tree Shaking 最彻底
  • 应用打包建议用 vite(底层 rollup + 更多工程化功能)
  • webpack 更适合复杂 SPA,插件生态更丰富

踩坑点

  • CommonJS 依赖需要 @rollup/plugin-commonjs 转换
  • Node.js 内置模块需要 @rollup/plugin-node-resolve
  • 动态导入支持有限,不如 webpack 成熟