Skip to content

Rollup

Rollup 是一个 JavaScript 模块打包器,专注于 JavaScript 库的打包。它使用 ES 模块系统,能够生成更小、更快的 bundle。Rollup 特别适合构建库和框架,而 Webpack 更适合构建应用程序。

核心概念

Entry

入口点指示 Rollup 应该从哪个模块开始构建其内部依赖图。

javascript
// rollup.config.js
export default {
  input: './src/index.js'
};

// 多个入口
const config = {
  input: {
    main: './src/index.js',
    utils: './src/utils.js'
  }
};

Output

output 属性告诉 Rollup 在哪里输出它所创建的 bundle,以及如何命名这些文件。

javascript
// rollup.config.js
export default {
  input: './src/index.js',
  output: {
    file: 'bundle.js',
    format: 'esm'
  }
};

// 多个输出
const config = {
  input: './src/index.js',
  output: [
    {
      file: 'bundle.cjs.js',
      format: 'cjs'
    },
    {
      file: 'bundle.esm.js',
      format: 'esm'
    },
    {
      file: 'bundle.umd.js',
      format: 'umd',
      name: 'MyLibrary'
    }
  ]
};

Plugins

插件可以扩展 Rollup 的功能,如转换代码、处理静态资源等。

javascript
// rollup.config.js
import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: './src/index.js',
  output: {
    file: 'bundle.js',
    format: 'esm'
  },
  plugins: [
    resolve(),
    commonjs(),
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**'
    })
  ]
};

External

external 属性告诉 Rollup 哪些模块应该被视为外部依赖,不应该被打包。

javascript
// rollup.config.js
export default {
  input: './src/index.js',
  output: {
    file: 'bundle.js',
    format: 'esm'
  },
  external: ['lodash', 'react']
};
加载中...

好好学习,天天向上