undefined
前言
Compile small pieces of code into something larger and more complex(官网)
下载依赖
通过命令行参数打包JS文件
-o src/main.js:指定输出文件路径
-f:转换输出格式
-f umd --name <name>:通用环境,通过--name <name>指定在浏览器环境中的全局变量名
-f cjs:CommonJS环境
-f iife:浏览器环境,需要手动修改最后一行})({})改为})(this)或})(window)
-f amd:AMD环境
1
| rollup src/main.js -o dist/bundle.js
|
通过配置文件打包JS文件
修改配置文件
output.name:指定打包后的当前包的浏览器全局变量名
output.globals:指定第三方依赖的浏览器全局变量
output.external:指定排除打包的第三方依赖,这种依赖需要用户手动引入
rollup.config.js1 2 3 4 5 6 7 8 9 10 11 12 13 14
| module.exports = { input: "src/main.js", output: { file: "dist/bundle.js", format: "umd", name: "<name>", globals: { "jquery": "$" }, external: [ "jquery" ] } };
|
打包为多个JS文件
rollup.config.js1 2 3 4 5 6 7 8 9 10 11 12 13 14
| module.exports = { input: "src/main.js", output: [ { file: "dist/bundle.js", format: "umd", name: "<name>" }, { file: "dist/bundle.cjs", format: "cjs" } ] };
|
支持CommonJS
- Rollup默认只支持ESModule,如果需要支持CommonJS,需要安装
@rollup/plugin-commonjs插件
1
| npm install -D @rollup/plugin-commonjs
|
rollup.config.js1 2 3 4 5 6 7
| const commonjs = require("@rollup/plugin-commonjs");
module.exports = { plugins: [ commonjs() ] };
|
打包node_modules中的依赖
1
| npm install -D @rollup/plugin-node-resolve
|
rollup.config.js1 2 3 4 5 6 7
| const resolve = require("@rollup/plugin-node-resolve");
module.exports = { plugins: [ resolve() ] };
|
打包JS文件
完成