用 Rollup 构建一款开源库

官网简介 : Rollup 是一个 JavaScript 模块打包器,能够将小块代码编译成大块复杂的代码,例如 library 或应用程序javascript

为何说 Rollup 一般适用于打包JS类库 ?html

  • 经过 rollup 打包后的代码,相比与 webpack 打出来的包体积会更小,并且代码会更加简洁,不会有过多的冗余代码。
  • rollup 也对 es 模块输出及 iife 格式打包有很好的支持

因此说 rollup 更适合构建一个组件库。rollup 和 webpack 的具体对比,本文章就不作扩展了。java

编写一个 TypeSript 组件

组件采用 TypeScript 的形式开发,因此先搭建基础的 TypeScript 开发环境node

npm init -yes // 生成基础的package.json
npm install -g typescript
tsc -init // 生成tsconfig.json
复制代码

在根目录建立一个src 文件 而且建立一个 utils.ts 文件编写组件内容,此时的文件目录是这样的react

rollupUtils
├── src
│   └── utils.ts
├── package.json
└── tsconfig.json
复制代码

先随便编写一个组件,这里编写了一个设置和获取 cookie 的方法
webpack

/* utils.js */

export const setCookie = (key: string, value: string) => {
  document.cookie = `${key}=${value};`;
};

export const getCookie = (key: string): string => {
  const items: string[] = document.cookie.split('; ');
  for (let i = 0; i < items.length; i += 1) {
    const item: string[] = items[i].split('=');
    if (key === item[0] && item.length === 2) {
      return decodeURIComponent(item[1]);
    }
  }
  return '';
};

复制代码

修改一下 tsconfig 的配置
git

/* tsconfig.json */

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "esnext"],
    "outDir": "lib",
    "declaration": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react"
  },
  "include": ["src"]
}

// 附上配置文档: https://www.tslang.cn/docs/handbook/compiler-options.html
复制代码

执行一下 tsc 命令,会根据 tsconfig.json 的配置进行编译 生成出一个 文件名为 lib 的包并将类型分离出来
es6

使用 Rollup 构建 UMD 包

UMD 叫作通用模块定义规范(Universal Module Definition) 就是一种javascript通用模块定义规范,让你的模块能在javascript全部运行环境中发挥做用。github

先安装一下 rollup 和解析 ts 的包web

npm i -D rollup rollup-plugin-typescript2 typescript
复制代码

在根目录建立一个 rollup.config.js

/* rollup.config.js */

import typescript from 'rollup-plugin-typescript2';
import { version } from './package.json';

export default {
  input: 'src/utils.ts',  // 入口文件
  output: {
    name: 'my_utils', // umd 模式必需要有 name  此属性做为全局变量访问打包结果
    file: `dist/@${version}/index.js`,
    format: 'umd',
    sourcemap: true,
  },
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          declaration: false, // 输出时去除类型文件
        },
      },
    }),
  ],
};

复制代码

执行 rollup -c 进行构建, 效果以下:

babel 编译

安装一系列的 babel 包

npm i -D @babel/core @babel/plugin-transform-runtime @babel/preset-env @rollup/plugin-babel @babel/preset-typescript
复制代码

建立 .babelrc 文件进行 babel 配置

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false,
        "loose": true,
        "targets": {
          "browsers": "> 1%, IE 11, not op_mini all, not dead",
          "node": 8
        }
      }
    ],
    ["@babel/preset-typeScript"]
  ]
}


复制代码

rollup.config.js 引入 babel

import { babel } from '@rollup/plugin-babel';
plugins:[
    babel({
      extensions: [".js", ".ts"],
      exclude: "node_modules/**",
      babelHelpers: 'bundled'
    }),
]
复制代码

执行 rollup -c 进行编译

lib 包是通过 tsc 命令 打包出来的 并无通过 babel 的处理。顺便处理一下吧

npm install @babel/cli -D
复制代码

先执行 tsc 生成 lib 包 再执行 babel 命令 babel lib --out-dir lib

压缩

安装一下 压缩插件

npm install -D rollup-plugin-terser
复制代码

rollup.config.js 添加上插件
最终的 rollup.config.js

/* rollup.config.js */

import typescript from 'rollup-plugin-typescript2';
import { babel } from '@rollup/plugin-babel';
import { terser } from 'rollup-plugin-terser';
import { version } from './package.json';

export default {
  input: 'src/utils.ts',
  output: {
    name: 'my_utils',
    file: `dist/@${version}/index.js`,
    format: 'umd',
    sourcemap: true,
  },
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          declaration: false,
        },
      },
    }),
    babel({
      extensions: [".js", ".ts"],
      exclude: "node_modules/**",
      babelHelpers: 'bundled'
    }),
    terser(),
  ],
};
复制代码

最后整理一下

删除 lib 文件夹 而后再执行 tsc 将 ts 文件 分离 xxx.d.ts 类型文件以及 js 文件 , 而后走一遍 babel 编译 lib 文件夹

执行 tsc 的目的是为了获取类型文件,若采用 TS 开发可引入此包

删除 dist 文件夹 再经过 rollup 打包出来 UMD 模式文件

这里再安利一个 插件 rimraf
从新打包的时候。须要把旧的打包文件删除,这里的用法也比较简单 rimraf <path> [<path> ...]

理清思路后 , 在package.json 下的 scripts 添加脚本
"build": "rimraf /lib/ && tsc && babel lib --out-dir lib && rimraf /dist/ && rollup -c"
接下来 执行一下 build 命令

校验结果:
在页面引入 <script src="dist/@1.0.0/index.js"></script>

此处 my_utils 就是 rollup.config.js -> output 里面的 name 属性

最后贴一下 github 地址:github.com/Coffee-C/ro…

相关文章
相关标签/搜索