rollup 快速上手指南

10/24/2022 rollup打包工具

# 起步

初始化项目

# 创建项目
mkdir rollup-starter

# 初始化项目
npm init -y

# 安装依赖
npm i -D rollup
1
2
3
4
5
6
7
8

安装 rollup 后,用 npx 执行 rollup,npx 可以找到 node_modules下的执行程序,不带参数默认输出 bundle 信息。

npx rollup
1

# 配置

在项目根目录下新建 rollup.config.js 文件

// rollup.config.js
export default {
  input: 'src/index.js', // 入口文件
  output: {
    file: 'dist/bundle.js', // 输出文件
    format: 'esm', // 文件输出格式
    name: 'bundleName', // 包的全局名称
  }
}
1
2
3
4
5
6
7
8
9

format:

  • amd: AMD 标准
  • cjs: commonjs标准
  • esm/es: ES模块标准
  • iife: 立即执行函数
  • umd: 同时支持 amd、cjs、iife

# 插件

插件是 rollup 唯一扩展途径。

// rollup.config.js
import json from 'rollup-plugin-json'
export default {
  plugins: [
    json(), // 可以在项目中导入 json 文件
  ]
}
1
2
3
4
5
6
7

# 加载 npm 模块

rollup 默认只能根据文件路径去加载本地模块, 无法直接加载第三方模块。

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve'
export default {
  plugins: [
    resolve(), // 可以在项目中直接导入第三方模块
  ]
}
1
2
3
4
5
6
7

# 加载 commonjs 模块

rollup 默认只处理 es 模块打包,不支持在项目中导入 commonjs 模块。

// rollup.config.js
import commonjs from 'rollup-plugin-commonjs'
export default {
  plugins: [
    resolve(), // 可以在项目中导入 commonjs 模块
  ]
}
1
2
3
4
5
6
7

# 代码拆分

项目使用动态导入,rollup 默认会进行代码拆分。

import('module').then({ fn } => {
  fn()
})
1
2
3

# 多入口打包

rollup 支持多入口打包,而且会将不同入口公共的部分提出到单个文件,作为独立的部分。

// rollup.config.js
export default {
  // input: ['src/index.js', 'src/index1.js'],
  input: {
    module: 'src/index.js',
    module1: 'src/index1.js'
  },
  output: {
    dir: 'dist',
    format: 'amd'
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
Last Updated: 11/24/2022, 3:09:33 PM