使用 npm 安装 Rollup:
npm install --save-dev rollup
基础使用
// rollup.config.js
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'iife',
name: 'MyBundle'
}
};
然后运行 Rollup:
npx rollup -c
使用插件
Rollup 支持多种插件,如处理 CommonJS 模块、转译 ES6 代码等。以下是一个使用 Babel 插件的示例:
// rollup.config.js
import babel from '@rollup/plugin-babel';
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'iife',
name: 'MyBundle'
},
plugins: [
babel({ babelHelpers: 'bundled' })
]
};
rollup.rollup:用于创建一个 Rollup 打包实例。
const bundle = await rollup.rollup(inputOptions);
await bundle.write(outputOptions);
inputOptions:输入配置选项。
input
:入口文件路径。plugins
:使用的插件数组。outputOptions:输出配置选项。
file
:输出文件路径。format
:输出格式,如 esm
、cjs
、iife
。name
:生成全局变量的名称,用于 iife
和 umd
格式。plugin:插件机制。
@rollup/plugin-node-resolve
:解析 Node.js 风格的模块。@rollup/plugin-commonjs
:将 CommonJS 模块转换为 ES 模块。@rollup/plugin-babel
:使用 Babel 转译代码。代码拆分 (Code Splitting) Rollup 支持将代码拆分为多个块,以便于按需加载:
// rollup.config.js
export default {
input: 'src/main.js',
output: {
dir: 'dist',
format: 'esm'
}
};
多入口 可以配置多个入口文件来生成多个输出文件:
// rollup.config.js
export default {
input: ['src/main.js', 'src/another.js'],
output: {
dir: 'dist',
format: 'esm'
}
};