Rollup:打包ESM
主要面向打包JavaScript类库。
使用方法
- 安装
npm install rollup -D
,同时在node_modules/.bin/目录下会安装有CLI程序。 - 使用
npx rollup <entry file> --format <module type> --file <output file>
来对指定的入口文件进行打包,其中–format后面的<module type>
指定打包后的模块遵循的模块规范(如iife – 立即调用函数表达式、cjs – CommonJS等等),–file<output file>
指定输出文件名。 - rollup默认开启了tree-shaking功能
配置文件
- 项目根目录下创建rollup.config.js文件,尽管该文件中的代码运行在node环境,但rollup支持在配置文件中使用ES Module。
- 该文件默认导出一个配置对象。
- 使用
npx rollup --config
来启动rollup读取默认的配置文件rollup.config.js。注意必须加上–config参数,否则Rollup默认不读取配置文件。同样,在–config 之后可以添加其他命名的配置文件。
插件
- Rollup仅仅是打包ESM,如果有其他需求,如加载其他类型资源、编译ES6+语法等等,则需要使用插件来扩展。
- 在配置文件中使用plugins字段添加插件,这里以rollup-plugin-json插件为例来说明
// rollup.config.js
import json from 'rollup-plugin-json';
export default {
input: './src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json()
]
}
加载NPM模块
Rollup只能使用路径的形式导入模块,并不能使用NPM模块的名称来加载NPM模块,因此需要使用rollup-plugin-node-resolve插件来加载NPM模块。
但可以在rollup的配置文件中使用名称来导入NPM模块,因为配置文件使用的是node环境。
import json from 'rollup-plugin-json';
import resolve from 'rollup-plugin-node-resolve';
export default {
input: './src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
json(),
resolve()
]
}
加载CommonJS模块
插件:rollup-plugin-commonjs
可以导入CommonJS规范的模块
代码拆分
动态导入
rollup支持动态导入import()
语法,但在分包的时候,就不能使用iife的打包格式了。浏览器环境下只能使用AMD模块规范(同样加载AMD模块还需要加载器require.js)。
export default {
input: './src/index.js',
output: {
// 由于要分包,所以这里指定打包目录,而不是file了
dir: 'dist',
format: 'amd'
},
多入口打包
对多入口打包中,入口文件引用的公共模块进行拆分打包为独立的文件。
export default {
// input: './src/index.js',
input: {
foo: 'src/index.js',
bar: 'src/album.js'
},
output: {
// file: 'index.js',
// format: 'iife'
dir: 'dist',
format: 'amd'
},
Parcel
安装
npm install parcel-bundler -D
同时在node_modules/.bin/目录下安装了CLI程序。
使用
- 零配置
- Parcel官方建议打包入口文件为html文件,在HTML文件中引入入口的JavaScript文件
- 支持开发服务器、liveReload、HMR、动态导入、自动下载NPM依赖包等特性
- 构建速度快(使用worker 进程去启用多核编译),webpack可以利用happypack插件达到这一目的。
# 启动parcel
npx parcel <entry file>