Skip to content

Rollup

简介

Rollup 是一个 JavaScript 模块打包器,专注于性能和 ES6 模块的处理。它使用新的标准化 ES 模块格式,而不是以前的特定解决方案,如 CommonJS 和 AMD。Rollup 允许你编写使用 ES6 模块语法的代码,然后高效地将其打包成单个文件用于浏览器和 Node.js。

核心特性

Tree Shaking

Rollup 的最大特点是内置支持 Tree Shaking(摇树优化),可以有效剔除未使用的代码,生成更小的包。

javascript
// 源代码
// math.js
export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}

// main.js
import { cube } from './math.js';
console.log(cube(5)); // 125

在最终打包中,square 函数会被自动剔除,因为它没有被使用。

简单配置

javascript
// rollup.config.js
export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  }
};

多种输出格式

Rollup 支持多种输出格式,包括:

  • ES 模块 (ESM)
  • CommonJS
  • UMD (Universal Module Definition)
  • IIFE (立即执行函数表达式)
  • System
javascript
export default {
  input: 'src/main.js',
  output: [
    {
      file: 'dist/bundle.cjs.js',
      format: 'cjs'
    },
    {
      file: 'dist/bundle.esm.js',
      format: 'esm'
    },
    {
      file: 'dist/bundle.umd.js',
      format: 'umd',
      name: 'myLibrary'
    }
  ]
};

插件系统

Rollup 拥有丰富的插件生态系统,可以扩展其功能:

javascript
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/main.js',
  output: {
    file: 'bundle.min.js',
    format: 'iife',
    name: 'myBundle'
  },
  plugins: [
    resolve(), // 解析 node_modules 中的模块
    commonjs(), // 将 CommonJS 模块转换为 ES6
    babel({ babelHelpers: 'bundled' }), // 转换 ES6+ 代码
    terser() // 压缩代码
  ]
};

常用插件

  1. @rollup/plugin-node-resolve - 解析 node_modules 中的依赖
  2. @rollup/plugin-commonjs - 将 CommonJS 模块转换为 ES6
  3. @rollup/plugin-babel - 使用 Babel 转换代码
  4. @rollup/plugin-terser - 压缩代码
  5. @rollup/plugin-typescript - 支持 TypeScript
  6. rollup-plugin-postcss - 处理 CSS 文件

适用场景

Rollup 特别适合:

  • 打包 JavaScript 库和框架
  • 需要高度优化包大小的项目
  • 使用 ES 模块的现代 JavaScript 项目
  • 需要生成多种模块格式的库

与其他打包工具对比

特性RollupWebpackVite
主要用途库和框架应用程序现代Web应用
配置复杂度简单复杂简单
Tree Shaking原生支持需配置支持
代码分割支持强大支持支持
热模块替换不支持支持极速支持
生态系统中等丰富快速成长

常见问题与解决方案

外部依赖处理

javascript
export default {
  input: 'src/main.js',
  external: ['lodash', 'react'], // 声明外部依赖
  output: {
    file: 'bundle.js',
    format: 'esm',
    globals: {
      lodash: '_',
      react: 'React'
    }
  }
};

代码分割

javascript
export default {
  input: ['src/main.js', 'src/another.js'],
  output: {
    dir: 'dist',
    format: 'esm',
    chunkFileNames: '[name]-[hash].js'
  }
};

学习资源