介绍
Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,使用ES6标准打包代码。
使用场景
在开发应用时使用 Webpack,开发库时使用 Rollup
开始
yarn init -y
安装依赖
yarn add rollup
配置rollup.config.js文件
export default {
input: "./src/index.js", // 程序入口
output: {//文件输出配置
file: "./dist/bundle.cjs.js", // 打包生成的文件位置和文件名
format: "cjs" // 输出格式
}
}
运行
yarn run rollup -c
rollup配置文件解析
- input
No.1.1 - output
format: 五种输出格式:amd / es6 / iife / umd / cjs
name: 当format为iife和umd时必须提供,将作为全局变量挂在window(浏览器环境)下:window.A=...
sourcemap:true //生成bundle.map.js文件,方便调试 - plugins 各种插件配置
rollup-plugin-node-resolve // 帮助寻找node_modules里的包
rollup-plugin-babel // rollup 的 babel 插件,ES6转ES5
rollup-plugin-replace // 替换待打包文件里的一些变量,如process在浏览器端是不存在的,需要被替换
rollup-plugin-commonjs // 将非ES6语法的包转为ES6可用
rollup-plugin-uglify // 压缩包 - external
external:['react'] //告诉rollup不要将此react打包,而作为外部依赖
- plugins
external: ['react', 'redux'], // 告诉rollup,不打包react,redux;将其视为外部依赖
globals: {
react: 'React', // 跟external 是配套使用的,指明global.React即是外部依赖react。
redux: 'Redux'
}
深入
为了正确解析我们的模块并使其与旧版浏览器兼容,使用babel来编译输出
- 安装 rollup-plugin-babel @babel/core 和 @babel/preset-env
cnpm install rollup-plugin-babel @babel/core @babel/preset-env -D
- 增加babel配置到 rollup.config.js
plugins: [
babel({exclude: 'node_modules/**'}) //排除依赖 只编译我们的源代码
]
- 添加Babel配置文件.babelrc
{
"presets":["@babel/preset-env"]
}