Rollup
相比于webpack,rollup要小巧的多,它仅仅是一款ES Module打包器,并不支持例如HMR等特性,它的初衷是提供一个充分利用ESM各项特性的高效打包器;
Rollup快速上手
yarn add roullup --dev
下载之后rollup会提供一个cli程序,可以通过yarn或者npx来执行,避免我们通过路径去查找cl(这里和前面我们手动写的xp-web工作流类似)
- Usage: rollup [options]
- 必须指定 --format,即打包后的格式(amd, cjs, system, esm, iife, umd);
- –file 指定打包后输出的文件(webpack会自动输出);
yarn rollup ./src/index.js --format iife --file ./dist/bundle.js
- rollup默认会开启tree-shaking,未引用部分都不会输出
Rollup配置文件
新建rollup.config.js,rollup必须手动指定配置文件
yarn rollup --config rollup.config.js
// rollup.config.js
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
}
}
Rollup插件
当我们需要加载其他类型的资源文件,编译新特性等,我们可以使用插件来拓展Rollup,插件是Rollup唯一拓展途径;
这里我们使用rooluo-plugin-json插件为例 yarn add rollup-plugin-json --dev
,将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()
]
}
//---------index.js文件中
import {
name } from '../package.json'
Rollup加载npm模块
rollup默认只能按照文件路径去加载本地模块,不能像webpack一样直接用名称去加载node_modules里面的对应模块;rollup默认只能处理ESM模块;
rollup-plugin-node-resolve