Rollup简易教程

Rollup是什么

Rollup是一个JavaScript模块打包工具,相对于Webpack更侧重于应用打包,Rollup更适合用来构建库。Rollup有着简单易用的API、支持Tree-shaking的特性,若你只是想为你的库构建出一个bundle包,Rollup会是非常不错的选择,业内不少优秀框架,如React、Vue都使用Rollup构建,本文将简单介绍Rollup的使用。

安装

1
npm install --global rollup

初始化演示项目

为了方便演示,使用 npm init 初始化package.json,并新建index.js、utils/math.js,形成这样的目录结构:

1
2
3
4
├── index.js
├── package.json
└── utils
└── math.js

在utils/math.js中,编写并导出两个工具函数

1
2
3
4
5
6
export const add = (x, y) => {
return x + y;
};
export const reduce = (x, y) => {
return x - y;
};

在index.js中,我们引用并打印add函数
1
2
3
import { add } from "./utils/math";

console.log(add(1,2));

Tree-shaking

接着我们演示Tree-shaking特性,运行打包命令:

1
rollup index.js --file output.js

以上命令代表执行打包index.js,–file参数表示指定输出的文件名,运行完毕后我们打开output.js:
1
2
3
4
5
const add = (x, y) => {
return x + y;
};

console.log(add(1,2));

可以看到,utils/math.js中的reduce函数由于没有在index.js中使用,所以被Tree-shaking处理了,并没有出现在打包产物中。

指定输出文件夹

1
rollup index.js --dir dirname

运行后会把打包产物输出到–dir参数后指定的文件夹中

指定产物构建格式

rollup支持打包成CommonJS、UMD、自执行函数(IIFE-style scripts for browsers),打包参数略有区别:

For browsers:

1
2
3
# compile to a <script> containing a self-executing function
rollup main.js --format iife --name "myBundle" --file bundle.js


For Node.js:
1
2
# compile to a CommonJS module
rollup main.js --format cjs --file bundle.js

For both browsers and Node.js:
1
2
# UMD format requires a bundle name
rollup main.js --format umd --name "myBundle" --file bundle.js

根据配置文件打包

作为bundle打包工具,rollup自然也支持根据配置文件进行打包,配置文件在区分环境时非常有用。我们可以于项目根目录新建一个rollup.config.js进行演示,内容为:

1
2
3
4
5
6
7
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};

上面的配置指定了输入输出以及输出格式,在使用时我们可以使用–config指定配置文件
1
rollup --config rollup.config.js

rollup的配置文件有很多玩法,具体可以参阅rollup-configuration-files


Rollup简易教程
http://yanziyu.fun/2022/10/25/rollup/
作者
Leo Yen
发布于
2022年10月25日
许可协议