Rollup

1. 介紹

Rollupwebpack作用類似,但Rollup更為小巧,僅僅是一款ESM打包器,Rollup中并不支持類似HMR這種高級(jí)特性

是為了提供一個(gè)充分利用ESM各種特性的高效打包器


2. 快速上手

2.1 安裝Rollup

$ yarn add rollup -D
// index.js
// 導(dǎo)入模塊成員
import { log } from './logger'
import messages from './messages'

// 使用模塊成員
const msg = messages.hi

log(msg)
// logger.js
export const log = msg => {
  console.log('---------- INFO ----------')
  console.log(msg)
  console.log('--------------------------')
}

export const error = msg => {
  console.error('---------- ERROR ----------')
  console.error(msg)
  console.error('---------------------------')
}
// message.js
export default {
  hi: 'Hey Guys, I am zce~'
}

2.2 運(yùn)行打包命令

$ yarn rollup ./index.js --file bundle.js

生成的bundle.js文件,代碼如下

const log = msg => {
  console.log('---------- INFO ----------');
  console.log(msg);
  console.log('--------------------------');
};

var messages = {
  hi: 'Hey Guys, I am zce~'
};

// 導(dǎo)入模塊成員

// 使用模塊成員
const msg = messages.hi;

log(msg);

打包后的代碼非常簡潔,就是將需要運(yùn)行的代碼按順序拼接到一起。注意,是只會(huì)保留到有用的代碼。這就是Rollup最早提出的Tree-shaking特性,后來幾乎被所有打包工具參考引入。


3. 配置文件

// rollup.config.js
export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife' // 輸出格式
  }
}

3.1 運(yùn)行

$ yarn rollup --config

4. 使用插件

如:加載其它類型資源模塊,導(dǎo)入CommosJS模塊,編譯ECMAScript新特性

注意:插件是Rollup唯一擴(kuò)展途徑

4.1 導(dǎo)入json文件

import json from 'rollup-plugin-json'

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife'
  },
  plugins: [
    json()
  ]
}

4.2 加載npm模塊

import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'

export default {
    ...
  plugins: [
    json(),
    resolve()
  ]
}

4.3 加載CommosJS模塊

import json from 'rollup-plugin-json'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'

export default {
  ...
  plugins: [
    json(),
    resolve(),
    commonjs()
  ]
}

5. 代碼拆分

// index.js
import('./logger').then(({ log }) => {
  log('code splitting~')
})
// rollup.config.js
export default {
  input: 'src/index.js',
  output: {
    dir: 'dist',
    format: 'amd'
  }
}

6. 多入口打包

export default {
  // input: ['src/index.js', 'src/album.js'],
  input: {
    foo: 'src/index.js',
    bar: 'src/album.js'
  },
  output: {
    dir: 'dist',
    format: 'amd'
  }
}

7. 總結(jié)

優(yōu)點(diǎn):

  • 輸出結(jié)果更加扁平
  • 自動(dòng)移除未引用代碼
  • 打包結(jié)果依然完全可讀

缺點(diǎn):

  • 加載非ESM的第三方模塊比較復(fù)雜
  • 模塊最終都被打包到一個(gè)函數(shù)中,無法實(shí)現(xiàn)HMR
  • 瀏覽器環(huán)境中,代碼拆分功能依賴AMD

如果我們正在開發(fā)應(yīng)用程序,建議使用webpack

如果開發(fā)一個(gè)框架或者類庫,可以選擇Rollup

?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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