Rollup 是一款高效的 ES Module 打包器。比起 webpack,Rollup 功能没有那样强大,但要小巧的多。

上手

安装

  1. yarn add rollup --dev

运行打包

Rollup 使用命令行打包,需要指定入口文件,打包输出格式 --format amd/cjs/esm/iife/umd,打包输出文件 --file。使用配置文件更方便一些,默认配置文件名rollup.config.js,或者运行打包命令时传入 --config 配置文件名
Rollup 打包默认会开启 tree shaking。

rollup.config.js:

  1. 使用 ES module 导出
  2. export default {
  3. input: 'src/index.js',
  4. output: {
  5. file: 'dist/bundle.js',
  6. format: 'iife'
  7. }
  8. }

插件

Rollup 本身只有打包 JS文件的功能,想要实现其它功能,需要通过插件来扩展。
rollup-plugin-json 用来加载 json 文件,rollup-plugin-node-resolve 用来加载 npm 模块,rollup-plugin-commonjs 用来加载 CommonJS 模块。

  1. import json from 'rollup-plugin-json'
  2. import resolve from 'rollup-plugin-node-resolve'
  3. import commonjs from 'rollup-plugin-commonjs'
  4. export default {
  5. input: 'src/index.js',
  6. output: {
  7. file: 'dist/bundle.js',
  8. format: 'iife'
  9. },
  10. plugins: [
  11. json(),
  12. resolve(),
  13. commonjs()
  14. ]
  15. }

代码拆分

Rollup 支持将动态导入的模块进行代码拆分,但是代码拆分必须使用 AMD 或者 CommonJS 标准,并且不能指定输出文件名。

  1. export default {
  2. input: 'src/index.js',
  3. output: {
  4. // file: 'dist/bundle.js',
  5. // format: 'iife'
  6. dir: 'dist',
  7. format: 'amd'
  8. }
  9. }

多入口打包

Rollup 多入口打包会自动拆分公共模块,所以多入口打包也不能使用 IIFE 或 UMD 标准。

  1. export default {
  2. // input: ['src/index.js', 'src/album.js'],
  3. input: {
  4. foo: 'src/index.js',
  5. bar: 'src/album.js'
  6. },
  7. output: {
  8. dir: 'dist',
  9. format: 'amd'
  10. }
  11. }

总结

Rollup 的输出结果更加扁平,而且自动开启未使用代码移除功能,打包结果可读性强。但是 Rollup 加载非 ES Modules 的第三方模块比较复杂;模块最终会被打包到一个函数中,无法实现 HMR;在浏览器环境中,代码拆分功能依赖像 require.js 这样的 AMD 库。
如果开发框架或者模块,Rollup 会比 webpack 更有优势,框架或模块的开发较少依赖第三库,而且本身是在非浏览器环境中开发的。如果开发一个 Web 应用,webpack 会更好。