###使用插件
---
到目前為止,我們已經(jīng)從一個入口點(diǎn)和通過相對路徑導(dǎo)入的模塊創(chuàng)建了一個簡單的bundle。當(dāng)您需要構(gòu)建更為復(fù)雜的bundle時,您通常需要更多的靈活性 - 例如導(dǎo)入使用npm來安裝的模塊、使用Babel編譯代碼、使用JSON文件等等。
針對以上原因,我們使用了 *插件*,它可以在打包過程的關(guān)鍵點(diǎn)改變Rollup的行為。在[the Rollup wiki](https://github.com/rollup/rollup/wiki/Plugins)上維護(hù)了可用插件的列表。
### 使用插件
在本教程中,我們將使用[rollup-plugin-json](https://github.com/rollup/rollup-plugin-json)作為例子,它允許Rollup從JSON文件導(dǎo)入數(shù)據(jù)。
首先安裝rollup-plugin-json作為開發(fā)依賴:
```bash
npm install --save-dev rollup-plugin-json
```
(我們使用`--save-dev`而不是`--save`,因?yàn)槲覀兊拇a實(shí)際上在運(yùn)行時不依賴于插件, - 只有當(dāng)我們構(gòu)建打包時才會使用到。)
然后更新您的`src/main.js`文件,以便它從您的package.json導(dǎo)入而不是從`src/foo.js`導(dǎo)入:
```js
// src/main.js
import { version } from '../package.json';
export default function () {
console.log('version ' + version);
}
```
其次編輯您的`rollup.config.js`文件以包含JSON插件:
```js
// rollup.config.js
import json from 'rollup-plugin-json';
export default {
entry: 'src/main.js',
format: 'cjs',
plugins: [ json() ],
dest: 'bundle.js'
};
```
最后通過命令`npm run build`來運(yùn)行Rollup。結(jié)果應(yīng)該是這樣子的:
```js
'use strict';
var version = "1.0.0";
var main = function () {
console.log('version ' + version);
};
module.exports = main;
```
(請注意,只有我們實(shí)際需要的數(shù)據(jù)才會被導(dǎo)入 - `name`和`devDependencies`以及package.json的其他部分是被忽略的。哪是因?yàn)閇tree-shaking](#what-is-tree-shaking-)在起作用!)
***
> 原文:https://rollupjs.org/#getting-started-with-plugins
