01-Rollup 概述
Rollup 是一款小巧的 JavaScript 模块打包器。它可以将多个 JavaScript 文件打包成一个或多个 bundle,并且支持使用 npm 或 CommonJS 模块加载。Rollup 适用于构建库、应用程序和插件等场景,它的特点包括:
- 使用 ES6 模块作为输入,输出为兼容性更好的 UMD 或 AMD 模块。
- 通过插件机制实现代码分割、压缩、混淆等优化功能。
- 支持使用 npm 或 CommonJS 模块加载,方便集成其他 JavaScript 库或框架。
- 跨平台,可以在不同操作系统上运行。
02-Rollup 快速上手
使用命令打包 esmodule 代码
npx rollup src/index.js --format iife -o dist/bundle.js
或者
npx rollup src/index.js --format iife --file dist/bundle.js
03-Rollup 配置文件
export default {
input: 'src/index.js', // 入口文件
output: {
file: 'dist/bundle.umd.js', // 导出路径
format: 'umd', // 导出格式
name: 'Banbi' // 模块导出的变量名
},
plugins: [
/// ...
]
}
04-Rollup 使用插件
插件 rollup-plugin-json 插件支持 import 导入 json 文件并转为对象
import json from 'rollup-plugin-json' // 插件支持 import 导入 json 文件
export default {
/// ...
plugins: [json()]
}
05-Rollup 加载 NPM 模块
rollup 默认只支持加载本地模块,如果需要加载 npm 模块,需要使用插件 rollup-plugin-node-resolve
06-Rollup 加载 CommonJS 模块
rollup 默认只支持加载 esmodule 模块,如果需要加载 CommonJS 模块,需要使用插件 rollup-plugin-commonjs
07-Rollup 代码拆分
入口文件使用 import() 动态导入,rollup 默认会自动拆分代码,如下入口文件index.js
import('./a.js').then(say => {
say('hello')
})
import('./b.js').then(say => {
say('BBBB')
})
打包后,生成的文件如下
index.js
a-f0df9k9.js
b-3fdfd0.js
08-Rollup 多入口打包
input 改为对象,键为入口文件名,值为入口文件路径,或者数组也可以
export default {
input: { foo: 'src/amd.js', bar: 'src/index.js' }, // 入口文件
output: {
dir: 'dist/entries', // 导出路径
format: 'amd', // 导出格式
name: 'Banbi', // 模块导出的变量名,
},
}
09-Rollup 选用原则
webpack 和 rollup 的选用原则
在选择 webpack 和 rollup 时,可以根据以下原则来决定:首先,了解项目需求,包括项目规模、需要支持的浏览器、是否需要代码拆分等。其次,考虑社区支持,webpack 在中大型项目中的使用更加广泛。再次,考虑配置复杂度,webpack 的配置相对复杂。另外,如果项目需要实现代码拆分和静态资源导入等功能,webpack 更适合。同时,rollup 在使用 ES6 模块和 Tree-shaking 算法优化代码方面有优势。最后,根据个人经验选择熟悉的工具。
10-Parcel
2017 年发布的,原因是 webpack 配置过于繁琐
傻瓜式打包器(0配置,让开发者专注业务开发),以index.html 为入口,支持开发热更新,自动安装第三方依赖,包拆分等等