來(lái)源:rollup.js 官網(wǎng)
有時(shí)候,項(xiàng)目會(huì)依賴(lài) npm 包。Rollup 和 Webpack、Browserify 不同,默認(rèn)不知道如何處理包之間的關(guān)系 --- 我們需要做一些配置。
舉個(gè)例子,我們需要一個(gè)簡(jiǎn)單的依賴(lài):the-answer,它會(huì)輸出人生、宇宙等終極問(wèn)題的答案:
npm install --save the-answer
# 簡(jiǎn)寫(xiě)形式:
npm i -S the-answer
注意到我們這次使用了 --save 選項(xiàng),所以它會(huì)存儲(chǔ)到 package.json 文件的 dependencies 字段。
如果我們更新了 src/main.js 文件...
import answer from 'the-answer';
export default function() {
console.log('the answer is ' + answer);
}
然后運(yùn)行 Rollup ...
npm run build
我們會(huì)看到一條警告:
'the-answer' is imported by src/main.js, but could not be resolved – treating it as an external dependency
輸出的結(jié)果 bundle.js 依然可以在 Node.js 中使用,因?yàn)?import 指令變成了 CommonJS 的 require 指令,但是 the-answer 沒(méi)有打包到結(jié)果中。為此,我們需要一個(gè)插件。
rollup-plugin-node-resolve
rollup-plugin-node-resolve 插件告訴 Rollup 如何搜尋外部依賴(lài)。安裝命令如下...
npm install --save-dev rollup-plugin-node-resolve
然后添加到你的配置文件:
// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
export default {
entry: 'src/main.js',
format: 'cjs',
plugins: [resolve()],
dest: 'bundle.js'
};
這次,當(dāng)你再次運(yùn)行 npm run build,就沒(méi)有警告了 --- 輸出文件包含引入的模塊了。
rollup-plugin-commonjs
有些庫(kù)象 the-answer 一樣,暴露了 ES6 風(fēng)格的模塊,可以如上所示引用。但是,目前 npm 上大多數(shù)模塊使用了 CommonJS 風(fēng)格。在此之前,需要將 CommonJS 轉(zhuǎn)換為 ES2015,然后才能供 Rollup 享用。
rollup-plugin-commonjs 就是這樣的插件。
注意,rollup-plugin-commonjs 需要在其他插件轉(zhuǎn)換代碼之前引入,這樣可以避免 CommonJS 語(yǔ)法規(guī)范被其他插件破壞。
下一篇:使用 Babel