简单说下rollup就是只将调用过的模块打包,做到尽量精简的打包。
使用webpack 1.X 版本是无法利用该特性来避免引入冗余模块代码的
webpack2 已经出来好几款 beta 版本了,同样也加上了对 Tree-shaking 的支持
1.src中的文件
jquery.js
1 | // 出口 |
init.js
1 | var init = function(jQuery){ |
2.安装包
pakage.json 包管理1
npm init
开始安装1
npm i rollup rollup-plugin-babel babel-preset-es2015-rollup --save-dev
3.编译
3.1 命令行编译
1 | rollup src/jquery.js --output bundle.js -f cjs |
3.1.1 编译成commonjs格式的文件
1 | ; |
另外还有几种格式1
amd / es6 / iife / umd
3.1.2 umd
1 | rollup src/jquery.js --output bundle.js -f umd |
会报错1
You must supply options.moduleName for UMD bundles
这是因为我们在jquery.js
中1
export default jQuery;
我们使用配置方式进行编译,就能指定导出的模块名moduleName: 'jQuery'
3.2 配置编译–rollup -c rollup.config.dev.js
rollup.config.dev.js
1 | import babel from 'rollup-plugin-babel'; |
src中.babelrc
1
2
3
4
5{
presets: [
["es2015", { "modules": false }]
]
}
注意{ "modules": false }
一定要有,否则一直报错,错误如下所示1
2
3
4
5
6
7
8
9Error transforming E:\javascript\rollup-demo\src\jquery.js with 'babel' plugin: It looks like your Babel configuration specifies a module transformer. Please disable it. If you're using the "es2015" preset, consider using "es2015-rollup" instead. See https://github.com/rollup/rollup-plugin-babel#configuring-babel f or more information
Error: Error transforming E:\javascript\rollup-demo\src\jquery.js with 'babel' plugin: It looks like your Babel configuration specifies a module transformer. Please disable it. If you're using the "es2015" preset, consider using "es2015- rollup" instead. See https://github.com/rollup/rollup-plugin-babel#configuring- babel for more information
at preflightCheck (E:\javascript\rollup-demo\node_modules\rollup-plugin-bab el\dist\rollup-plugin-babel.cjs.js:43:102)
at Object.transform$1 [as transform] (E:\javascript\rollup-demo\node_module s\rollup-plugin-babel\dist\rollup-plugin-babel.cjs.js:104:18)
at C:\Users\Ruyi\AppData\Roaming\npm\node_modules\rollup\src\utils\transfor m.js:19:35
at process._tickCallback (node.js:379:9)
at Function.Module.runMain (module.js:459:11)
at startup (node.js:138:18)
at node.js:974:3
命令1
rollup -c rollup.config.dev.js
3.3 配置编译–node rollup.config.dev.js
rollup.config.dev.js
1 | var rollup = require( 'rollup' ); |
参考阅读: