[note] rollup-js 筆記
keywords: 打包
, bundle
rollup.js @ official website
Quick Start
可以參考 Rollup 的這兩個啟動專案:
- rollup-starter-lib:用 rollup.js 建立套件的起始架構
- rollup-starter-app:用 rollup.js 建立應用程式的起始架構
假設應用程式的進入點(entry point)是 main.js
,打包後的檔案稱作 bundle.js
,則
給瀏覽器(iife
):
# compile to a <script> containing a self-executing function ('iife')
rollup main.js --file bundle.js --format iife
給 Node.js(cjs
):
# compile to a CommonJS module ('cjs')
rollup main.js --file bundle.js --format cjs
同時給瀏覽器和 Node.js(umd
):
# UMD format requires a bundle name
rollup main.js --file bundle.js --format umd --name "myBundle"
發佈 ES Modules
為了確保你的 ES Modules 可以立即 Node.js 或 Webpack 這類 CommonJS 的工具所使用,你可以使用 Rollup 來編譯成 UMD 或 CommonJS 的格式,接著在 package.json
中的 main
屬性指定該打包好的檔案,如果你的 package.json
中也有 module
這個屬性,則 ESM-aware 的工具(例如,Rollup 和 web pack 2+)將會直接載入 ES Module 的版本。
Plugins
- rollup plugins @ rollupjs Github
- using-output-plugin @ rollupjs docs
- rollup-plugin-terser @ github
- @rollup/plugin-commonjs:可以將以 CommonJS 寫的模組轉換成 ES6,如此就可以在 Rollup 中匯入 CommonJS 的模組。
- @rollup/plugin-node-resolve:rollup 才會解析
node_modules
裡面的第三方套件,如果自己的套件中有用到其他第三方的套件時需安裝。 - rollup-plugin-terser:可以用來壓縮打包後的檔案
Command Line Interface (CLI)
Command Line 可用參數
Command line flags @ rollup.js > CLI
# 直接透過 CLI 打包
# -f 是 --format <format>, -o 是 --file <output>
$ rollup index.js -f cjs -o bundle.js
# 根據 rollup.config.js 打包
# -c 是 --config <filename>,沒填 filename 預設會直接吃 rollup.config.js
$ rollup -c