Rollup 是一个 JavaScript 模块打包器
安装
npm install --global rollup
简单示例
main.js
console.log("hello rollup");
打包
rollup --help # 可以查看 # 浏览器 rollup main.js --file bundle.js --format iife
打包结果
bundle.js
(function () { "use strict"; console.log("hello rollup"); })();
第一个 Buddle
src/main.js
// src/main.js import foo from "./foo.js"; export default function () { console.log(foo); }
src/foo.js
// src/foo.js export default "hello world!";
打包
rollup src/main.js -o bundle.js -f cjs
使用配置文件
rollup.config.js
// rollup.config.js export default { input: "src/main.js", output: { file: "bundle.js", format: "cjs", }, };
打包
# 默认使用rollup.config.js rollup -c
插件
https://github.com/rollup/plugins/
npm init -y npm install --save-dev rollup-plugin-json
从 json 文件中读取数据
package.json
{ "name": "rollup-demo", "version": "1.0.0", "description": "", "main": "", "dependencies": {}, "devDependencies": { "rollup-plugin-json": "^4.0.0" }, "scripts": { "build": "rollup -c" }, "keywords": [], "author": "", "license": "ISC" }
src/main.js
// src/main.js import { version } from "../package.json"; export default function () { console.log("version " + version); }
配置文件加入 JSON 插件
rollup.config.js
// rollup.config.js import json from "rollup-plugin-json"; export default { input: "src/main.js", output: { file: "bundle.js", format: "cjs", }, plugins: [json()], };
编译
npm run build
编译结果
"use strict"; var version = "1.0.0"; // src/main.js function main() { console.log("version " + version); } module.exports = main;
总结
配置打包和开发环境启动项
package.json
{ "name": "rollup-demo", "version": "1.0.0", "description": "", "main": "", "dependencies": {}, "devDependencies": { "rollup-plugin-json": "^4.0.0" }, "scripts": { "dev": "rollup --config --watch", "build": "rollup --config" }, "keywords": [], "author": "", "license": "ISC" }
配置即使打包
rollup.config.js
// rollup.config.js import json from "rollup-plugin-json"; export default { input: "src/main.js", output: { file: "bundle.js", format: "iife", }, plugins: [json()], watch: { exclude: "node_modules/**", }, };