Vue3 企業級優雅實戰 – 組件庫框架 – 5 組件庫通用工具包

該系列已更新文章:
分享一個實用的 vite + vue3 組件庫腳手架工具,提升開發效率
開箱即用 yyg-cli 腳手架:快速創建 vue3 組件庫和vue3 全家桶項目
Vue3 企業級優雅實戰 – 組件庫框架 – 1 搭建 pnpm monorepo
Vue3 企業級優雅實戰 – 組件庫框架 – 2 初始化 workspace-root
Vue3 企業級優雅實戰 – 組件庫框架 – 3 搭建組件庫開發環境
Vue3 企業級優雅實戰 – 組件庫框架 – 4 組件庫的 CSS 架構

本文繼續組件庫開發環境的搭建,前面兩篇分別介紹了組件庫中組件項目的初始化、組件庫 CSS 架構,本文介紹通用工具庫的搭建。在組件開發過程中,可能會調用一些通用的工具函數,這些工具函數便可以提取到一個獨立的 npm 包中。

1 創建工具包

1.1 初始化工具包

到目前為止,packages 目錄下有三個包:foo 示例組件、scss 樣式、yyg-demo-ui 組件庫聚合,現創建第四個:utils

在命令行中進入 utils 目錄,使用 pnpm 初始化。

pnpm init

修改自動生成的 package.json 文件中的 namemain ,內容如下:

{
  "name": "@yyg-demo-ui/utils",
  "version": "1.0.0",
  "description": "通用工具函數",
  "main": "index.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

由於工具包咱們也採用 TypeScript 編寫,在 utils 下也提供一份 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "es2015",
    "lib": [
      "es2015"
    ],
    "module": "commonjs",
    "rootDir": "./",
    "allowJs": true,
    "isolatedModules": false,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

1.2 編寫第一個工具函數

需求描述:組件間通信是一個剛需,當組件層級較多時,可以使用全局總線來通信。Vue 2.x 中通常使用 EventBus 作為全局總線,而 Vue 3.x 可以使用 mittmitt 體積小,支持全部事件的監聽和批量移除,不依賴 Vue 實例,可以跨框架使用。咱們的第一個工具函數就是簡單封裝 mitt,導出 mitt 對象即可。

首先在 utils 包下安裝 mitt 依賴:

pnpm install [email protected]

細心的同學會發現,在引入 mitt 時優雅哥指定了版本號 1.1.3,這是因為,優雅哥在使用當前最新的 3.0.0 版本時一直提示類型錯誤或找不到類型聲明文件,由於沒空處理,就簡單粗暴的降到 1.1.3 版本。

utils 目錄下創建源碼目錄 src,並在 src 中創建 emitter.ts 文件。

utils/src/emitter.ts

import mitt from 'mitt'
const Mitt = mitt
export const emitter: mitt.Emitter = new Mitt()

export default emitter

上面的第二行代碼看着多餘,因為本質上就是 new mitt(),這麼做是為了滿足 eslint 的規則:

A constructor name should not start with a lowercase letter.

1.3 編寫第二個工具函數

上面的 emitter 對象會在後面的組件開發中使用到,在 foo 中並未使用到,所以咱們再創建一個測試使用的工具函數。

utils/src/ 目錄下創建 test-log.ts 文件:

export const testLog = (str: string) => {
  console.log('test log: ', str)
}

1.4 入口文件

前面的 package.json 中指定了 mainindex.ts,在 utils 目錄下創建 index.ts 文件,導入並導出所有的工具函數等。

export { emitter } from './src/emitter'
export { testLog } from './src/test-log'

總結一下,組件庫通用工具包的目錄結構如下:

packages/
  |- utils/
    |- src/
        |- emitter.ts
        |- test-log.ts
    |- index.ts
    |- tsconfig.json
    |- package.json

2 在組件中使用工具包

2.1 安裝依賴

前面已經開發了 foo 示例組件,如果該組件要使用工具包,首先需要安裝依賴。在命令行中進入 foo 目錄:

pnpm install @yyg-demo-ui/utils

執行後 foo 的 package.json 中會多了一行依賴:

"dependencies": {
  "@yyg-demo-ui/utils": "workspace:^1.0.0"
}

2.2 使用工具

由於 utils 包指定了 mainindex.ts,並且所有的工具都在 index.ts 中導入並導出,所以在使用時只需引入 utils 包即可。

例如要使用上面創建的 testLog 函數,則只需要在代碼中如下引入:

import { testLog } from '@yyg-demo-ui/utils'

setup 中的按鈕點擊事件調用該方法:

const onBtnClick = () => {
  console.log('點擊按鈕測試', props.msg)
  testLog(props.msg)
}

後面再開發過程中如果新增工具函數:如 JSON Schema 的解析等,則往 utils 中添加即可,並在 utils/index.ts 中統一將其導入並導出。

感謝你閱讀本文,如果本文給了你一點點幫助或者啟發,還請三連支持一下,點贊、關注、收藏,程序員優雅哥會持續與大家分享更多乾貨