介紹
Rollup 是一個(gè) JavaScript 模塊打包器,可以將小塊代碼編譯成大塊復(fù)雜的代碼,使用ES6標(biāo)準(zhǔn)打包代碼。
使用場(chǎng)景
在開發(fā)應(yīng)用時(shí)使用 Webpack,開發(fā)庫時(shí)使用 Rollup
開始
yarn init -y
安裝依賴
yarn add rollup
配置rollup.config.js文件
export default {
input: "./src/index.js", // 程序入口
output: {//文件輸出配置
file: "./dist/bundle.cjs.js", // 打包生成的文件位置和文件名
format: "cjs" // 輸出格式
}
}
運(yùn)行
yarn run rollup -c
rollup配置文件解析
- input
No.1.1 - output
format: 五種輸出格式:amd / es6 / iife / umd / cjs
name: 當(dāng)format為iife和umd時(shí)必須提供,將作為全局變量掛在window(瀏覽器環(huán)境)下:window.A=...
sourcemap:true //生成bundle.map.js文件,方便調(diào)試 - plugins 各種插件配置
rollup-plugin-node-resolve // 幫助尋找node_modules里的包
rollup-plugin-babel // rollup 的 babel 插件,ES6轉(zhuǎn)ES5
rollup-plugin-replace // 替換待打包文件里的一些變量,如process在瀏覽器端是不存在的,需要被替換
rollup-plugin-commonjs // 將非ES6語法的包轉(zhuǎn)為ES6可用
rollup-plugin-uglify // 壓縮包 - external
external:['react'] //告訴rollup不要將此react打包,而作為外部依賴
- plugins
external: ['react', 'redux'], // 告訴rollup,不打包react,redux;將其視為外部依賴
globals: {
react: 'React', // 跟external 是配套使用的,指明global.React即是外部依賴react。
redux: 'Redux'
}
深入
為了正確解析我們的模塊并使其與舊版瀏覽器兼容,使用babel來編譯輸出
- 安裝 rollup-plugin-babel @babel/core 和 @babel/preset-env
cnpm install rollup-plugin-babel @babel/core @babel/preset-env -D
- 增加babel配置到 rollup.config.js
plugins: [
babel({exclude: 'node_modules/**'}) //排除依賴 只編譯我們的源代碼
]
- 添加Babel配置文件.babelrc
{
"presets":["@babel/preset-env"]
}