Rollup打包

介紹

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"]
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容