初衷:提供一个充分利用ESM(ES Module)各项特性的高效打包器
安装:yarn add rolluo --dev 用法: yarn rollup //不传递任何参数的情况下,打印Rollup的帮助信息 yarn rollup ./src/index.js --format iife //执行index.js文件并以iife(自调用函数)的方式输出(--format指定输出格式) yarn rollup ./src/index.js --format iife --file dist/bundle.js //输出文件到dist/bundle.js 默认开启chunk去掉多余代码,优化输出结果
export default { input: 'src/index.js', output: { file: 'dist/bundle.js', format: 'iife' } }
插件是Rollup的扩展途径
Rollup默认只能根据文件路径加载本地的文件模块,第三方模块不能直接通过模块名称去导入
rollup-plugin-node-resolve:安装后Rollup可直接通过模块名称导入模块 安装:yarn add rollup-plugin-node-resolve --dev
import resolvefrom 'rollup-plugin-node-resolve' export default { input: 'src/index.js', output: { file: 'dist/bundle.js', format: 'iife' }, plugins: [ resolve() ] }
rollup-plugin-commonjs:因为Rollup默认只能处理ESM模块,使用这个插件Rollup就可以处理CommonJS
安装:yarn add rollup-plugin-commonjs --dev
import commonjsfrom 'rollup-plugin-commonjs' export default { input: 'src/index.js', output: { file: 'dist/bundle.js', format: 'iife' }, plugins: [ commonjs() ] }
运行:yarn rollup
import('./logger').then(({ log }) => { log('code splitting~') })
export default { input: 'src/index.js', output: { dir: 'dist', format: 'amd' } }
多入口打包内部会自动提取公共模块,也就是说内部会使用代码拆分
export default { input: ['src/index.js', 'src/album.js'], output: { dir: 'dist', format: 'amd' } }
export default { input: { foo: 'src/index.js', bar: 'src/album.js' }, output: { dir: 'dist', format: 'amd' } }
Rollup优势:
输出结果更加扁平(执行效率更高)
自动移除未引用的代码
打包结果依然完全可读(和手写代码一致)
Rollup缺点:
加载非ESM的第三方模块比较复杂(需要配置一大堆插件)
模块最终都被打包到一个函数中,无法实现HMR
浏览器环境中,代码拆分功能依赖AMD库
选用:
开发应用程序 选用Webpack,大而全
开发框架或类库 选用Rollup,小而美
零配置的前端应用打包器
安装:
yarn add parcel-bundler --dev
运行:
yarn parcel src/index.html //index.html为入口文件
优势:
支持自动安装依赖 支持动态导入 相同体量下,Parcel比Webpack打包要快,因为Parcel使用的是多进程同时工作,充分发挥了多核CPU的性能(Webpack也可以使用happypack插件实现多进程)