⚡⚡⚡Rollup 简易入门

2,380 阅读2分钟

Rollup介绍及使用

1、Rollup 概述

  1. 仅仅是 ES Module 的打包器
  2. Rollup 与 Webpack 作用类似,相比于Webpack,Rollup更为小巧
  3. Rollup 中并不支持类似 HRM 特性

初衷:提供一个充分利用ESM(ES Module)各项特性的高效打包器

2、Rollup 快速上手

安装: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去掉多余代码,优化输出结果

3、Rollup 配置文件

rollup.config.js

export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    }
}

4、Rollup 使用插件

插件是Rollup的扩展途径

rollup.config.js

import jsonfrom 'rollup-plugin-json'
export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
format: 'iife'
    },
    plugins: [
        json()
    ]
}

5、Rollup 加载 NPM 模块

Rollup默认只能根据文件路径加载本地的文件模块,第三方模块不能直接通过模块名称去导入

rollup-plugin-node-resolve:安装后Rollup可直接通过模块名称导入模块

安装:yarn add rollup-plugin-node-resolve --dev

rollup.config.js

import resolvefrom 'rollup-plugin-node-resolve'
export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
format: 'iife'
    },
    plugins: [
        resolve()
    ]
}

6、Rollup 加载 CommonJS 模块

rollup-plugin-commonjs:因为Rollup默认只能处理ESM模块,使用这个插件Rollup就可以处理CommonJS

安装:yarn add rollup-plugin-commonjs --dev

rollup.config.js

import commonjsfrom 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
    output: {
        file: 'dist/bundle.js',
format: 'iife'
    },
    plugins: [
        commonjs()
    ]
}

7、Rollup 代码拆分

运行:yarn rollup

index.js

import('./logger').then(({ log }) => {
    log('code splitting~')
})

rollup.config.js

export default {
	input: 'src/index.js',
	  output: {
	      dir: 'dist',
	      format: 'amd'
  }
}

8、Rollup 多入口打包

多入口打包内部会自动提取公共模块,也就是说内部会使用代码拆分

rollup.config.js

方式1:

export default {
input: ['src/index.js', 'src/album.js'],
    output: {
        dir: 'dist',
        format: 'amd'
    }
}

方式2:

export default {
input: {
        foo: 'src/index.js',
        bar: 'src/album.js'
    },
output: {
dir: 'dist',
        format: 'amd'
    }
}

9、Rollup 选用原则

Rollup优势:
    输出结果更加扁平(执行效率更高)
    自动移除未引用的代码
    打包结果依然完全可读(和手写代码一致)

Rollup缺点:
    加载非ESM的第三方模块比较复杂(需要配置一大堆插件)
    模块最终都被打包到一个函数中,无法实现HMR
    浏览器环境中,代码拆分功能依赖AMD库

选用:
    开发应用程序    选用Webpack,大而全
    开发框架或类库  选用Rollup,小而美

10、Parcel

零配置的前端应用打包器
安装:

yarn add parcel-bundler --dev 

运行:

yarn parcel src/index.html 
//index.html为入口文件 

优势:
支持自动安装依赖 支持动态导入 相同体量下,Parcel比Webpack打包要快,因为Parcel使用的是多进程同时工作,充分发挥了多核CPU的性能(Webpack也可以使用happypack插件实现多进程)