用 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…

相關文章
相關標籤/搜索