###使用 Rollup 和 npm 程序包
---
某些時候,很可能你的項目會依賴于 npm 安裝到 `node_modules` 文件夾中的程序包。跟其它打包工具如 Webpack 和 Browserify 不同,Rollup 不知道如何去開箱即用地處理這些依賴 - 我們需要添加一些配置。
讓我們添加一個簡單的依賴,叫 [the-answer](https://www.npmjs.com/package/the-answer), 它輸出對生活、宇宙及其它一切的答案:
```bash
npm install --save the-answer # or `npm i -S the-answer`
```
注意我們這次使用 `--save`,因為這樣它會被保存到 package.json 的 `dependencies` 部份。
如果我們更新 `src/main.js` 文件...
```js
// src/main.js
import answer from 'the-answer';
export default function () {
console.log('the answer is ' + answer);
}
```
...運行 Rollup...
```bash
npm run build
```
...我們會看到下面的警告:
```
?? 'the-answer' is imported by src/main.js, but could not be resolved – treating it as an external dependency
?? 'the-answer' 被 src/main.js 引用,但不知道如何去解析 - 把它看作是外部的以來
```
生成的 `bundle.js` 在 Node.js 中仍然能運行,因為 `import` 聲音被編譯為 CommonJS 的 `require` 語句,但 `the-answer` *并沒有* 被打包到文件束中。為此,我們需要一個插件。
### rollup-plugin-node-resolve
[rollup-plugin-node-resolve](https://github.com/rollup/rollup-plugin-node-resolve) 插件指導 Rollup 如果去尋找外部的模塊。請安裝...
```bash
npm install --save-dev rollup-plugin-node-resolve
```
...將它添加到你的配置文件中:
```js
// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
export default {
entry: 'src/main.js',
format: 'cjs',
plugins: [ resolve() ],
dest: 'bundle.js'
};
```
這次,當你運行 `npm run build`, 再沒有警告輸出 - 文件束包含了引用的模塊。
### rollup-plugin-commonjs
一些庫輸出 ES6 模塊,你可以照原來的樣子引用 - `the-answer` 正是這樣的一個模塊。但當下,大部份 npm 的程序包都被輸出為 CommonJS 模塊。直到它改變,在 Rollup 處理它們之前,我們都需要將 CommonJS 轉成 ES2015。
[rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs) 插件就正好來處理這件事。
注意 `rollup-plugin-commonjs` 應該在其它插件變換你的模塊之前使用 - 這是為了避免其它插件做了一些改變,而這改變會破壞了 CommonJS 的檢測。
## Peer dependencies
比方說,你正在開發一個有 peer dependency 的庫,例如 React 或者 Lodash。如果你像上面描述的那樣設置 externals,你的 rollup 會打包 *所有的* 引用:
```js
import answer from 'the-answer';
import _ from 'lodash';
```
你可以很好地調整哪些需要被打包,哪些應該看作外部引用 (external)。在這個例子里,我們把 `lodash` 看作外部引用(external),而不是 `ths-answer`。這里是配置文件:
```js
// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
export default {
entry: 'src/main.js',
format: 'cjs',
plugins: [resolve({
// 給 resolve 插件傳入自定配置
customResolveOptions: {
moduleDirectory: 'node_modules'
}
})],
// 指明哪個模塊被看作外部引用(external)
external: ['lodash'],
dest: 'bundle.js'
};
```
看, `lodash` 現在被看成外部引用(external),而沒有被打包進你的庫中。
`external` 參數接受一個模塊名稱的數組,或者一個函數,這個函數接收模塊名,如果它被看作外部引用(external),會返回 true。例如:
```js
export default {
// ...
external: id => /lodash/.test(id)
}
```
你可能會使用這個形式的插件 [babel-plugin-lodash](https://github.com/lodash/babel-plugin-lodash) 去擇優挑選 lodash 模塊。這個請況下, Babel 會將你的引用語句轉化成如下代碼:
```js
import _merge from 'lodash/merge';
```
如果 `external` 是數組形式,它不會處理通配符(*),所以這種引用只有在函數形式的時候,才會被看作外部引用(external)。
***
> 原文:https://rollupjs.org/#using-rollup-with-npm