Rollup 是一款高效的 ES Module 打包器。比起 webpack,Rollup 功能没有那样强大,但要小巧的多。
上手
安装
yarn add rollup --dev
运行打包
Rollup 使用命令行打包,需要指定入口文件,打包输出格式 --format amd/cjs/esm/iife/umd
,打包输出文件 --file
。使用配置文件更方便一些,默认配置文件名rollup.config.js
,或者运行打包命令时传入 --config 配置文件名
。
Rollup 打包默认会开启 tree shaking。
rollup.config.js:
使用 ES module 导出
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
}
}
插件
Rollup 本身只有打包 JS文件的功能,想要实现其它功能,需要通过插件来扩展。
rollup-plugin-json 用来加载 json 文件,rollup-plugin-node-resolve 用来加载 npm 模块,rollup-plugin-commonjs 用来加载 CommonJS 模块。
import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json(),
resolve(),
commonjs()
]
}
代码拆分
Rollup 支持将动态导入的模块进行代码拆分,但是代码拆分必须使用 AMD 或者 CommonJS 标准,并且不能指定输出文件名。
export default {
input: 'src/index.js',
output: {
// file: 'dist/bundle.js',
// format: 'iife'
dir: 'dist',
format: 'amd'
}
}
多入口打包
Rollup 多入口打包会自动拆分公共模块,所以多入口打包也不能使用 IIFE 或 UMD 标准。
export default {
// input: ['src/index.js', 'src/album.js'],
input: {
foo: 'src/index.js',
bar: 'src/album.js'
},
output: {
dir: 'dist',
format: 'amd'
}
}
总结
Rollup 的输出结果更加扁平,而且自动开启未使用代码移除功能,打包结果可读性强。但是 Rollup 加载非 ES Modules 的第三方模块比较复杂;模块最终会被打包到一个函数中,无法实现 HMR;在浏览器环境中,代码拆分功能依赖像 require.js 这样的 AMD 库。
如果开发框架或者模块,Rollup 会比 webpack 更有优势,框架或模块的开发较少依赖第三库,而且本身是在非浏览器环境中开发的。如果开发一个 Web 应用,webpack 会更好。