Cheat Sheet速查表
跳转到主要内容

Rollup.js 速查表

本文根据 Devhints / Rollup.js 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2020-01-29。

Rollup Rollup 是一个用于 JavaScript 的模块打包工具,它将小的代码片段编译成更大、更复杂的产物,例如库或应用程序。

基本配置

rollup.config.js

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  }
}

终端

npm install -D rollup
命令说明
rollup -c -o bundle.js使用配置进行打包
rollup main.js --o bundle.js --f cjs打包
rollup --watch持续打包

您可能需要使用 ./node_modules/.bin/rollup 作为命令,前提是您没有全局安装 rollup。

多个输出

rollup.config.js

export default [
  {
    input: 'src/main.js',
    output: {
      file: __dirname + '/public/main.js',
      format: 'cjs',
      name: 'main'
    }
  },
  {
    input: 'src/vendor.js',
    output: {
      file: __dirname + 'public/vendor.js',
      format: 'cjs',
      name: 'vendor'
    }
  }
]

这将创建 main.js 以及 vendor.js.

使用插件

插件 (Plugins)

终端

npm install -D @rollup/plugin-json

rollup.config.js

import json from '@rollup/plugin-json'

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

npm 软件包

终端

npm install -D @rollup/plugin-node-resolve

rollup.config.js

import resolve from '@rollup/plugin-node-resolve'

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [ resolve() ]
}

当您运行 npm 构建命令时,不会发出任何警告,且产物中包含了导入的模块。

对等依赖 (Peer dependencies)

终端

npm install -D @rollup/plugin-node-resolve

rollup.config.js

import resolve from '@rollup/plugin-node-resolve'

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [resolve({
    // pass custom options to the resolve plugin
    customResolveOptions: {
      moduleDirectory: 'node_modules'
    }
  })],
  // indicate which modules should be treated as external
  external: ['lodash']
}

Babel

终端

npm install -D @rollup/plugin-babel

rollup.config.js

import resolve from '@rollup/plugin-node-resolve'
import babel from '@rollup/plugin-babel'

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
    resolve(),
    babel({
      exclude: 'node_modules/**' // only transpile our source code
    })
  ]
}

src/.babelrc

{
  "presets": [
    ["latest", {
      "es2015": {
        "modules": false
      }
    }]
  ],
  "plugins": ["external-helpers"]
}