1. 介绍
Rollup
与webpack
作用类似,但Rollup
更为小巧,仅仅是一款ESM
打包器,Rollup
中并不支持类似HMR
这种高级特性
是为了提供一个充分利用ESM
各种特性的高效打包器
2. 快速上手
2.1 安装Rollup
$ yarn add rollup -D
// index.js
// 导入模块成员
import { log } from './logger'
import messages from './messages'
// 使用模块成员
const msg = messages.hi
log(msg)
// logger.js
export const log = msg => {
console.log('---------- INFO ----------')
console.log(msg)
console.log('--------------------------')
}
export const error = msg => {
console.error('---------- ERROR ----------')
console.error(msg)
console.error('---------------------------')
}
// message.js
export default {
hi: 'Hey Guys, I am zce~'
}
2.2 运行打包命令
$ yarn rollup ./index.js --file bundle.js
生成的bundle.js
文件,代码如下
const log = msg => {
console.log('---------- INFO ----------');
console.log(msg);
console.log('--------------------------');
};
var messages = {
hi: 'Hey Guys, I am zce~'
};
// 导入模块成员
// 使用模块成员
const msg = messages.hi;
log(msg);
打包后的代码非常简洁,就是将需要运行的代码按顺序拼接到一起。注意,是只会保留到有用的代码
。这就是Rollup
最早提出的Tree-shaking
特性,后来几乎被所有打包工具参考引入。
3. 配置文件
// rollup.config.js
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife' // 输出格式
}
}
3.1 运行
$ yarn rollup --config
4. 使用插件
如:加载其它类型资源模块,导入CommosJS
模块,编译ECMAScript
新特性
注意:插件是Rollup
唯一扩展途径
4.1 导入json
文件
import json from 'rollup-plugin-json'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json()
]
}
4.2 加载npm
模块
import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
export default {
...
plugins: [
json(),
resolve()
]
}
4.3 加载CommosJS
模块
import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
...
plugins: [
json(),
resolve(),
commonjs()
]
}
5. 代码拆分
// index.js
import('./logger').then(({ log }) => {
log('code splitting~')
})
// rollup.config.js
export default {
input: 'src/index.js',
output: {
dir: 'dist',
format: 'amd'
}
}
6. 多入口打包
export default {
// input: ['src/index.js', 'src/album.js'],
input: {
foo: 'src/index.js',
bar: 'src/album.js'
},
output: {
dir: 'dist',
format: 'amd'
}
}
7. 总结
优点:
- 输出结果更加扁平
- 自动移除未引用代码
- 打包结果依然完全可读
缺点:
- 加载非
ESM
的第三方模块比较复杂 - 模块最终都被打包到一个函数中,无法实现
HMR
- 浏览器环境中,代码拆分功能依赖
AMD
库
如果我们正在开发应用程序,建议使用webpack
如果开发一个框架或者类库,可以选择Rollup
网友评论