Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,例如 library 或应用程序。Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中,而不是以前的特殊解决方案,如 CommonJS 和 AMD。ES6 模块可以使你自由、无缝地使用你最喜爱的 library 中那些最有用独立函数,而你的项目不必携带其他未使用的代码。ES6 模块最终还是要由浏览器原生实现,但当前 Rollup 可以使你提前体验。

Rollup允许我们以ES6来进行库的开发,通常我们用Webpack来打包应用类的项目,而使用Rollup来打包库类型的项目,因为Rollup可以使我们的库更加简洁。

快速上手

安装

  1. npm install --global rollup

Rollup提供两种方式来使用:命令行接口JavaScript API

使用rollup --help查看使用命令及相关参数。

基本使用命令:

rollup [options] <entry file>

如打包一个支持Commonjs的文件:

rollup main.js --file bundle.js --format cjs

可以使用rollup-starter-lib库来初始化项目

配置文件

// rollup.config.js
export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  }
};

上面是最基础的配置,指定input打包入口和output输出文件名称及类型

另外针对处理输入文件和处理输出文件都提供了相应的插件。
如官方实例:

import json from 'rollup-plugin-json';

export default {
    input: 'src/main.js',
    output: {
        file: 'bundle.js',
        format: 'cjs'
    },
    plugins: [ json() ]
}

另外我们也可以使用插件对输出文件进行处理,如使用rollup-plugin-terser对打包文件进行压缩:

yarn add -D rollup-plugin-terser

配置:

import { terser } from 'rollup-plugin-terser';

export default {
        input: 'src/main.js',
        output: [
            { file: 'bundle.js', format: 'cjs' },
            { file: 'bundle.min.js', format: 'iife', name: 'version', plugin: [terser()] }
        ]
}

另外,上面的配置文件默认一种打包配置,也可以指定多种打包配置,如:

export default [
    // browser-friendly UMD build
    {
        input: 'src/index.ts',
        output: {
            name: 'test',
            file: pkg.browser,
            format: 'umd'
        },
        plugins: [
            commonjs(), // so Rollup can convert `ms` to an ES module
            typescript(), // so Rollup can convert TypeScript to js
        ]
    },

    {
        input: 'src/index.ts',
        plugins: [
            typescript(), // so Rollup can convert TypeScript to js
        ],
        output: [
            { file: pkg.main, format: 'cjs' },
            { file: pkg.module, format: 'es' }
        ]
    }
];

搭配React + TypeScript

增加TypeScript支持

首先安装TS相关依赖:

yard add -D rollup-plugin-typescript ts-node tslib typescript

rollup.config.js:

import typescript from 'rollup-plugin-typescript';
export default { 
    plugins: [ typescript() ]
}

在项目目录下增加tsconfig.json文件,具体配置参考:tsconfig.json

搭配antd的babel-plugin-import使用

安装插件rollup-plugin-babelbabel-plugin-import

import babel from 'rollup-plugin-babel';
export default { 
    //plugins: [ babel() ]
    plugins: [
        babel({
            exclude: 'node_modules/**',
            extensions: ['.jsx', '.tsx', '.js', '.ts']
        })
    ]
}

参考:https://github.com/ant-design/babel-plugin-import及https://github.com/rollup/rollup-plugin-babel

总体来说,Rollup上手还是比较方便的,第一次用来打包业务的通用模块,体验很好,后续会继续研究,毕竟业务中通用库都倡导使用Rollup来打包,以保证更小的包体积。

来关注一波公号吧:
公众号二维码.jpg