手把手教你擼一個React元件庫(超詳細)

海秋發表於2020-05-15

概覽

本文包含以下內容:

  • prepare: 元件庫前期開發準備工作。eslint/commit lint/typescript等等;
  • dev: 使用docz進行開發除錯以及文件編寫;
  • build: umd/cjs/esm、types、polyfill 以及按需載入;
  • test: 元件測試;
  • release: 元件庫釋出流程;
  • deploy: 使用now部署文件站點,待補充;
  • other: 使用plop.js快速建立元件模板。

如果本文幫助到了你請給倉庫 一顆 ✨✨。

如果有錯誤煩請在評論區指正交流,謝謝。

倉庫地址

準備工作

初始化專案

新建一個happy-ui資料夾,並初始化。

mkdir happy-ui

cd happy-ui

npm init --y

mkdir components && cd components && touch index.ts # 新建原始碼資料夾以及入口檔案

程式碼規範

此處直接使用@umijs/fabric的配置。

yarn add @umijs/fabric --dev

yarn add prettier --dev # 因為@umijs/fabric沒有將prettier作為依賴 所以我們需要手動安裝

.eslintrc.js

module.exports = {
  extends: [require.resolve('@umijs/fabric/dist/eslint')],
};

.prettierrc.js

const fabric = require('@umijs/fabric');

module.exports = {
  ...fabric.prettier,
};

.stylelintrc.js

module.exports = {
  extends: [require.resolve('@umijs/fabric/dist/stylelint')],
};

想自行配置的同學可以參考以下文章:

Commit Lint

進行pre-commit程式碼規範檢測。

yarn add husky lint-staged --dev

package.json

"lint-staged": {
  "components/**/*.ts?(x)": [
    "prettier --write",
    "eslint --fix",
    "git add"
  ],
  "components/**/*.less": [
    "stylelint --syntax less --fix",
    "git add"
  ]
},
"husky": {
  "hooks": {
    "pre-commit": "lint-staged"
  }
}

進行 Commit Message 檢測。

yarn add @commitlint/cli @commitlint/config-conventional commitizen cz-conventional-changelog --dev

新增.commitlintrc.js寫入以下內容

module.exports = { extends: ['@commitlint/config-conventional'] };

package.json 寫入以下內容:

// ...
"scripts": {
  "commit": "git-cz",
}
// ...
"husky": {
  "hooks": {
    "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
    "pre-commit": "lint-staged"
  }
},
"config": {
  "commitizen": {
    "path": "cz-conventional-changelog"
  }
}

後續使用 yarn commit 替代 git commit生成規範的 Commit Message,當然為了效率你可以選擇手寫,但是要符合規範。

TypeScript

yarn add typescript --dev

新建tsconfig.json並寫入以下內容

{
  "compilerOptions": {
    "baseUrl": "./",
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "declarationDir": "lib",
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "include": ["components", "global.d.ts"],
  "exclude": ["node_modules"]
}

測試

components資料夾下新建alert資料夾,目錄結構如下:

alert
    ├── alert.tsx           # 原始檔
    ├── index.ts            # 入口檔案
    ├── interface.ts        # 型別宣告檔案
    └── style
        ├── index.less      # 樣式檔案
        └── index.ts        # 樣式檔案裡為什麼存在一個index.ts - 按需載入樣式 管理樣式依賴 後面章節會提到

安裝React相關依賴:

yarn add react react-dom @types/react @types/react-dom --dev # 開發時依賴,宿主環境一定存在

yarn add prop-types            # 執行時依賴,宿主環境可能不存在 安裝本元件庫時一起安裝
此處依舊安裝了prop-types這個庫,因為無法保證宿主環境也使用typescript,從而能夠進行靜態檢查,故使用prop-types保證javascript使用者也能得到友好的執行時報錯資訊。

components/alert/interface.ts

export type Kind = 'info' | 'positive' | 'negative' | 'warning';
export type KindMap = Record<Kind, string>;

export interface AlertProps {
  /**
   * Set this to change alert kind
   * @default info
   */
  kind?: 'info' | 'positive' | 'negative' | 'warning';
}

components/alert/alter.tsx

import React from 'react';
import t from 'prop-types';

import { AlertProps, KindMap } from './interface';

const prefixCls = 'happy-alert';

const kinds: KindMap = {
  info: '#5352ED',
  positive: '#2ED573',
  negative: '#FF4757',
  warning: '#FFA502',
};

const Alert: React.FC<AlertProps> = ({ children, kind = 'info', ...rest }) => (
  <div
    className={prefixCls}
    style={{
      background: kinds[kind],
    }}
    {...rest}
  >
    {children}
  </div>
);

Alert.propTypes = {
  kind: t.oneOf(['info', 'positive', 'negative', 'warning']),
};

export default Alert;

components/alert/index.ts

import Alert from './alert';

export default Alert;

export * from './interface';

components/alert/style/index.less

@popupPrefix: happy-alert;

.@{popupPrefix} {
  padding: 20px;
  background: white;
  border-radius: 3px;
  color: white;
}

components/alert/style/index.ts

import './index.less';

components/index.ts

export { default as Alert } from './alert';
此處元件參考的docz專案typescript以及less示例。

git 一把梭,可以看到控制檯已經進行鉤子檢測了。

git add .

yarn commit  # 或 git commit -m'feat: chapter-1 準備工作'

git push

準備工作完成。程式碼可以在倉庫chapter-1分支獲取,若存在與本文內容不符的地方,以master分支以及文章為準。

開發與除錯

本節解決開發元件時的預覽以及除錯問題,順路解決文件編寫。

此處選擇docz來輔助預覽除錯。

docz基於MDX(Markdown + JSX),可以在 Markdown 中引入 React 元件,使得一邊編寫文件,一邊預覽除錯成為了可能。而且得益於 React 元件生態,我們可以像編寫應用一般編寫文件,不僅僅是枯燥的文字。docz 也內建了一些元件,比如<Playground>

安裝 docz 以及自定義配置

yarn add docz --dev

yarn add rimraf --dev # 清空目錄的一個輔助庫

增加 npm scriptspackage.json

"scripts": {
  "dev": "docz dev", // 啟動本地開發環境
  "start": "npm run dev", // dev命令別名
  "build:doc": "rimraf doc-site && docz build", // 後續會配置打包出來的檔案目錄名為doc-site,故每次build前刪除
  "preview:doc": "docz serve" // 預覽文件站點
},
注意:本節所有操作都是針對站點應用。打包指代文件站點打包,而非元件庫。

新建doczrc.js配置檔案,並寫入以下內容:

doczrc.js

export default {
  files: './components/**/*.{md,markdown,mdx}', // 識別的檔案字尾
  dest: 'doc-site', // 打包出來的檔案目錄名
  title: 'happy-ui', // 站點標題
  typescript: true, // 元件原始檔是通過typescript開發,需要開啟此選項
};

由於使用了less作為樣式前處理器,故需要安裝 less 外掛。

yarn add less gatsby-plugin-less --dev

新建gatsby-config.js,並寫入以下內容:

gatsby-config.js

module.exports = {
  plugins: ['gatsby-theme-docz', 'gatsby-plugin-less'],
};

編寫文件

新建components/alert/index.mdx,並寫入以下內容:

---
name: Alert 警告提示
route: /Alert
menu: 元件
---

import { Playground } from 'docz'; import Alert from './alert'; // 引入元件 import './style'; // 引入元件樣式

# Alert 警告提示

警告提示,展現需要關注的資訊。

## 程式碼演示

### 基本用法

<Playground>
  <Alert kind="warning">這是一條警告提示</Alert>
</Playground>

## API

| 屬性 | 說明     | 型別                                         | 預設值 |
| ---- | -------- | -------------------------------------------- | ------ |
| kind | 警告型別 | 'info'/'positive'/'negative'/'warning'非必填 | 'info' |

執行指令碼命令:

yarn start # or yarn dev

可以在localhost:3000看到如下頁面 :

文件站點

現在可以在index.mdx中愉快地進行文件編寫和除錯了!

倘若本文到了這裡就結束(其實也可以結束了(_^▽^_)),那我只是官方文件的翻譯復讀機罷了,有興趣的同學可以繼續向下看。

優化文件編寫

如果程式碼演示部分的demo較多(比如基本用法、高階用法以及各種用法等等),在元件複雜的情況下(畢竟<Alert/>著實太簡單了),會導致文件很長難以維護,你到底是在寫文件呢還是在寫程式碼呢?

那就抽離吧。

components/alert/資料夾下新建demo資料夾,存放我們在編寫文件時需要引用的 demo

components/alert/demo/1-demo-basic.tsx

import React from 'react';
import Alert from '../alert';
import '../style';

export default () => <Alert kind="warning"></Alert>;

components/alert/index.mdx

- import Alert from './alert'; // 引入元件
- import './style'; // 引入元件樣式
+ import BasicDemo from './demo/1-demo-basic';

...

<Playground>
- <Alert kind="warning">這是一條警告提示</Alert>
+ <BasicDemo />
</Playground>

這樣我們就將 demo 與文件進行了分隔。預覽如下:

文件重構

等等,下面顯示的是<BasicDemo />,而非demo原始碼。

<Playground />元件暫時無法支援上述形式的展示:自定義下方展示的程式碼,而非<Playground />內部的程式碼。相關討論如下:

其實第一條 PR 已經解決了問題,但是被關閉了,無奈。

不過既然都能引入 React 元件了,在MDX的環境下自定義一個Playground元件又有何難呢,無非就是渲染元件(MDX 自帶)和展示原始碼,簡單開放的東西大家都是喜聞樂見的,就叫HappyBox吧。

優化程式碼展示

編寫 <HappyBox />元件

安裝依賴:

yarn add react-use react-tooltip react-feather react-simple-code-editor prismjs react-copy-to-clipboard raw-loader styled-components --dev
  • react-use - 2020 年了,當然要用hooks
  • react-simple-code-editor - 程式碼展示區域
  • prismjs - 程式碼高亮
  • raw-loader - 將原始碼轉成字串
  • react-copy-to-clipboard - 讓使用者爸爸們能夠 copy demo 程式碼
  • react-tooltip/react-feather 輔助元件
  • styled-components 方便在文件示例中讓使用者看到樣式,也用作文件元件的樣式處理
這些依賴都是服務於文件站點應用,和元件庫自身毫無關聯。

最終效果如下:

最終效果

根目錄下新建doc-comps資料夾,存放文件中使用的一些工具元件,比如<HappyBox />

doc-comps

├── happy-box
│   ├── style.ts
│   └── index.tsx
└── index.ts

components/doc-comps/happy-box/index.tsx

import React from 'react';
import Editor from 'react-simple-code-editor';
import CopyToClipboard from 'react-copy-to-clipboard';
import { useToggle } from 'react-use';
import ReactTooltip from 'react-tooltip';
import IconCopy from 'react-feather/dist/icons/clipboard';
import IconCode from 'react-feather/dist/icons/code';
import { highlight, languages } from 'prismjs/components/prism-core';
import { StyledContainer, StyledIconWrapper } from './style';

import 'prismjs/components/prism-clike';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-markup';

require('prismjs/components/prism-jsx');

interface Props {
  code: string;
  title?: React.ReactNode;
  desc?: React.ReactNode;
}

export const HappyBox: React.FC<Props> = ({ code, title, desc, children }) => {
  const [isEditVisible, toggleEditVisible] = useToggle(false);

  return (
    <StyledContainer>
      <section className="code-box-demo"> {children}</section>
      <section className="code-box-meta">
        <div className="text-divider">
          <span>{title || '示例'}</span>
        </div>
        <div className="code-box-description">
          <p>{desc || '暫無描述'}</p>
        </div>
        <div className="divider" />
        <div className="code-box-action">
          <CopyToClipboard text={code} onCopy={() => alert('複製成功')}>
            <IconCopy data-place="top" data-tip="複製程式碼" />
          </CopyToClipboard>

          <StyledIconWrapper onClick={toggleEditVisible}>
            <IconCode data-place="top" data-tip={isEditVisible ? '收起程式碼' : '顯示程式碼'} />
          </StyledIconWrapper>
        </div>
      </section>
      {renderEditor()}
      <ReactTooltip />
    </StyledContainer>
  );

  function renderEditor() {
    if (!isEditVisible) return null;
    return (
      <div className="container_editor_area">
        <Editor
          readOnly
          value={code}
          onValueChange={() => {}}
          highlight={code => highlight(code, languages.jsx)}
          padding={10}
          className="container__editor"
          style={{
            fontFamily: '"Fira code", "Fira Mono", monospace',
            fontSize: 14,
          }}
        />
      </div>
    );
  }
};

export default HappyBox;

相關配置變更

  • 增加 alias別名,樣例原始碼展示相對路徑不夠友好,讓使用者直接拷貝才夠省心

新建gatsby-node.js,寫入以下內容以開啟alias

const path = require('path');

exports.onCreateWebpackConfig = args => {
  args.actions.setWebpackConfig({
    resolve: {
      modules: [path.resolve(__dirname, '../src'), 'node_modules'],
      alias: {
        'happy-ui/lib': path.resolve(__dirname, '../components/'),
        'happy-ui/esm': path.resolve(__dirname, '../components/'),
        'happy-ui': path.resolve(__dirname, '../components/'),
      },
    },
  });
};

tsconfig.json 打包時需要忽略demo,避免元件庫打包生成types時包含其中,同時增加paths屬性用於 vscode 自動提示:

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./",
+   "paths": {
+     "happy-ui": ["components/index.ts"],
+     "happy-ui/esm/*": ["components/*"],
+     "happy-ui/lib/*": ["components/*"]
+    },
    "target": "esnext",
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "declarationDir": "lib",
    "strict": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "include": ["components", "global.d.ts"],
- "exclude": ["node_modules"]
+ "exclude": ["node_modules",  "**/demo/**"]
}

新的問題出現了,vscode 的 alias 提示依賴 tsconfig.json,忽略 demo 資料夾後,demo 內的檔案模組型別找不到宣告(paths 失效),所以不能將 demo 在 tsconfig.json 中移除:

{
- "exclude": ["node_modules",  "**/demo/**"]
+ "exclude": ["node_modules"]
}

新建一個 tsconfig.build.json 檔案:

tsconfig.build.json

{
  "extends": "./tsconfig.json",
  "exclude": ["**/demo/**", "node_modules"]
}

後續使用 tsc 生成型別宣告檔案指定tsconfig.build.json即可。

改造相關檔案

components/alert/demo/1-demo-basic.tsx

- import Alert from '../alert';
+ import Alert from 'happy-ui/lib/alert';

- import '../style';
+ import 'happy-ui/lib/alert/style';

components/alert/index.mdx

- import { Playground } from 'docz';
+ import { HappyBox } from '../../doc-comps';

+ import BasicDemoCode from '!raw-loader!./demo/1-demo-basic.tsx';

...

- <Playground>
-   <BasicDemo />
- </Playground>

+ <HappyBox code={BasicDemoCode} title="基本用法" desc="使用kind控制Alert型別">
+  <BasicDemo />
+ </HappyBox>
yarn start卡住時嘗試刪除根目錄.docz資料夾,而後重新執行命令。

現在可以愉快地開發元件了。程式碼可以在倉庫chapter-2分支獲取,若存在與本文內容不符的地方,以master分支以及文章為準。

元件庫打包

宿主環境各不相同,需要將原始碼進行相關處理後釋出至 npm。

明確以下目標:

  1. 匯出型別宣告檔案
  2. 匯出 umd/Commonjs module/ES module 等 3 種形式供使用者引入
  3. 支援樣式檔案 css 引入,而非只有less
  4. 支援按需載入

匯出型別宣告檔案

既然是使用typescript編寫的元件庫,那麼使用者應當享受到型別系統的好處。

我們可以生成型別宣告檔案,並在package.json中定義入口,如下:

package.json

{
  "typings": "types/index.d.ts", // 定義型別入口檔案
  "scripts": {
    "build:types": "tsc -p tsconfig.build.json" // 執行tsc命令生成型別宣告檔案
  }
}

tsconfig.build.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": { "emitDeclarationOnly": true }, // 只生成宣告檔案
  "exclude": ["**/__tests__/**", "**/demo/**", "node_modules", "lib", "esm", "types"] // 排除示例、測試以及打包好的資料夾
}

執行yarn build:types,可以發現根目錄下已經生成了lib資料夾(tsconfig.json中定義的outDir欄位),目錄結構與components資料夾保持一致,如下:

types

├── alert
│   ├── alert.d.ts
│   ├── index.d.ts
│   ├── interface.d.ts
│   └── style
│       └── index.d.ts
└── index.d.ts

這樣使用者引入npm 包時,便能得到自動提示,也能夠複用相關元件的型別定義。

接下來將ts(x)等檔案處理成js檔案。

需要注意的是,我們需要輸出Commonjs module以及ES module兩種模組型別的檔案(暫不考慮umd),以下使用cjs指代Commonjs moduleesm指代ES module。<br/> 對此有疑問的同學推薦閱讀:import、require、export、module.exports 混合詳解

匯出 Commonjs 模組

其實完全可以使用babeltsc命令列工具進行程式碼編譯處理(實際上很多工具庫就是這樣做的),但考慮到還要處理樣式及其按需載入,我們藉助 gulp 來串起這個流程。

babel 配置

首先安裝babel及其相關依賴

yarn add @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-proposal-class-properties  @babel/plugin-transform-runtime --dev
yarn add @babel/runtime-corejs3

新建.babelrc.js檔案,寫入以下內容:

.babelrc.js

module.exports = {
  presets: ['@babel/env', '@babel/typescript', '@babel/react'],
  plugins: [
    '@babel/proposal-class-properties',
    [
      '@babel/plugin-transform-runtime',
      {
        corejs: 3,
        helpers: true,
      },
    ],
  ],
};

關於@babel/plugin-transform-runtime@babel/runtime-corejs3

  • helpers選項設定為true,可抽離程式碼編譯過程重複生成的 helper 函式(classCallCheck,extends等),減小生成的程式碼體積;
  • corejs設定為3,可引入不汙染全域性的按需polyfill,常用於類庫編寫(我更推薦:不引入polyfill,轉而告知使用者需要引入何種polyfill,避免重複引入或產生衝突,後面會詳細提到)。

更多參見官方文件-@babel/plugin-transform-runtime

配置目標環境

為了避免轉譯瀏覽器原生支援的語法,新建.browserslistrc檔案,根據適配需求,寫入支援瀏覽器範圍,作用於@babel/preset-env

.browserslistrc

>0.2%
not dead
not op_mini all

很遺憾的是,@babel/runtime-corejs3無法在按需引入的基礎上根據目標瀏覽器支援程度再次減少polyfill的引入,參見@babel/runtime for target environment

這意味著@babel/runtime-corejs3 甚至會在針對現代引擎的情況下注入所有可能的 polyfill:不必要地增加了最終捆綁包的大小。

對於元件庫(程式碼量可能很大),個人建議將polyfill的選擇權交還給使用者,在宿主環境進行polyfill。若使用者具有相容性要求,自然會使用@babel/preset-env + core-js + .browserslistrc進行全域性polyfill,這套組合拳引入了最低目標瀏覽器不支援API的全部 polyfill

業務開發中,將@babel/preset-envuseBuiltIns選項值設定為 usage,同時把node_modulesbabel-loaderexclude掉的同學可能想要這個特性:"useBuiltIns: usage" for node_modules without transpiling #9419,在未支援該issue提到的內容之前,還是乖乖地將useBuiltIns設定為entry,或者不要把node_modulesbabel-loaderexclude

所以元件庫不用畫蛇添足,引入多餘的polyfill,寫好文件說明,比什麼都重要(就像zentantd這樣)。

現在@babel/runtime-corejs3更換為@babel/runtime,只進行helper函式抽離。

yarn remove @babel/runtime-corejs3

yarn add @babel/runtime

.babelrc.js

module.exports = {
  presets: ['@babel/env', '@babel/typescript', '@babel/react'],
  plugins: ['@babel/plugin-transform-runtime', '@babel/proposal-class-properties'],
};
@babel/transform-runtimehelper選項預設為true

gulp 配置

再來安裝gulp相關依賴

yarn add gulp gulp-babel --dev

新建gulpfile.js,寫入以下內容:

gulpfile.js

const gulp = require('gulp');
const babel = require('gulp-babel');

const paths = {
  dest: {
    lib: 'lib', // commonjs 檔案存放的目錄名 - 本塊關注
    esm: 'esm', // ES module 檔案存放的目錄名 - 暫時不關心
    dist: 'dist', // umd檔案存放的目錄名 - 暫時不關心
  },
  styles: 'components/**/*.less', // 樣式檔案路徑 - 暫時不關心
  scripts: ['components/**/*.{ts,tsx}', '!components/**/demo/*.{ts,tsx}'], // 指令碼檔案路徑
};

function compileCJS() {
  const { dest, scripts } = paths;
  return gulp
    .src(scripts)
    .pipe(babel()) // 使用gulp-babel處理
    .pipe(gulp.dest(dest.lib));
}

// 並行任務 後續加入樣式處理 可以並行處理
const build = gulp.parallel(compileCJS);

exports.build = build;

exports.default = build;

修改package.json

package.json

{
- "main": "index.js",
+ "main": "lib/index.js",
  "scripts": {
    ...
+   "clean": "rimraf types lib esm dist",
+   "build": "npm run clean && npm run build:types && gulp",
    ...
  },
}

執行yarn build,得到如下內容:

lib

├── alert
│   ├── alert.js
│   ├── index.js
│   ├── interface.js
│   └── style
│       └── index.js
└── index.js

觀察編譯後的原始碼,可以發現:諸多helper方法已被抽離至@babel/runtime中,模組匯入匯出形式也是commonjs規範。

lib/alert/alert.js

lib/alert/alert.js

匯出 ES module

生成ES module可以更好地進行tree shaking,基於上一步的babel配置,更新以下內容:

  1. 配置@babel/preset-envmodules選項為false,關閉模組轉換;
  2. 配置@babel/plugin-transform-runtimeuseESModules選項為true,使用ES module形式引入helper函式。

.babelrc.js

module.exports = {
  presets: [
    [
      '@babel/env',
      {
        modules: false, // 關閉模組轉換
      },
    ],
    '@babel/typescript',
    '@babel/react',
  ],
  plugins: [
    '@babel/proposal-class-properties',
    [
      '@babel/plugin-transform-runtime',
      {
        useESModules: true, // 使用esm形式的helper
      },
    ],
  ],
};

目標達成,我們再使用環境變數區分esmcjs(執行任務時設定對應的環境變數即可),最終babel配置如下:

.babelrc.js

module.exports = {
  presets: ['@babel/env', '@babel/typescript', '@babel/react'],
  plugins: ['@babel/plugin-transform-runtime', '@babel/proposal-class-properties'],
  env: {
    esm: {
      presets: [
        [
          '@babel/env',
          {
            modules: false,
          },
        ],
      ],
      plugins: [
        [
          '@babel/plugin-transform-runtime',
          {
            useESModules: true,
          },
        ],
      ],
    },
  },
};

接下來修改gulp相關配置,抽離compileScripts任務,增加compileESM任務。

gulpfile.js

// ...

/**
 * 編譯指令碼檔案
 * @param {string} babelEnv babel環境變數
 * @param {string} destDir 目標目錄
 */
function compileScripts(babelEnv, destDir) {
  const { scripts } = paths;
  // 設定環境變數
  process.env.BABEL_ENV = babelEnv;
  return gulp
    .src(scripts)
    .pipe(babel()) // 使用gulp-babel處理
    .pipe(gulp.dest(destDir));
}

/**
 * 編譯cjs
 */
function compileCJS() {
  const { dest } = paths;
  return compileScripts('cjs', dest.lib);
}

/**
 * 編譯esm
 */
function compileESM() {
  const { dest } = paths;
  return compileScripts('esm', dest.esm);
}

// 序列執行編譯指令碼任務(cjs,esm) 避免環境變數影響
const buildScripts = gulp.series(compileCJS, compileESM);

// 整體並行執行任務
const build = gulp.parallel(buildScripts);

// ...

執行yarn build,可以發現生成了types/lib/esm三個資料夾,觀察esm目錄,結構同lib/types一致,js 檔案都是以ES module模組形式匯入匯出。

esm/alert/alert.js

esm/alert/alert.js

別忘了給package.json增加相關入口。

package.json

{
+ "module": "esm/index.js"
}

處理樣式檔案

拷貝 less 檔案

我們會將less檔案包含在npm包中,使用者可以通過happy-ui/lib/alert/style/index.js的形式按需引入less檔案,此處可以直接將 less 檔案拷貝至目標資料夾。

gulpfile.js中新建copyLess任務。

gulpfile.js

// ...

/**
 * 拷貝less檔案
 */
function copyLess() {
  return gulp
    .src(paths.styles)
    .pipe(gulp.dest(paths.dest.lib))
    .pipe(gulp.dest(paths.dest.esm));
}

const build = gulp.parallel(buildScripts, copyLess);

// ...

觀察lib目錄,可以發現 less 檔案已被拷貝至alert/style目錄下。

lib

├── alert
│   ├── alert.js
│   ├── index.js
│   ├── interface.js
│   └── style
│       ├── index.js
│       └── index.less # less檔案
└── index.js

可能有些同學已經發現問題:若使用者沒有使用less前處理器,使用的是sass方案甚至原生css方案,那現有方案就搞不定了。經分析,有以下 3 種預選方案:

  1. 告知使用者增加less-loader
  2. 打包出一份完整的 css 檔案,進行全量引入;
  3. 單獨提供一份style/css.js檔案,引入的是元件 css樣式檔案依賴,而非 less 依賴,元件庫底層抹平差異;
  4. 使用css in js方案。

方案 1 會導致業務方使用成本增加。

方案 2 無法進行按需引入。

方案 4 需要詳細聊聊。

css in js除了賦予樣式編寫更多的可能性之外,在編寫第三方元件庫時更是利器。

如果我們寫一個react-use這種hooks工具庫,不涉及到樣式,只需要在package.json中設定sideEffectsfalse,業務方使用 webpack 進行打包時,只會打包被使用到的 hooks(優先使用 ES module)。

入口檔案index.js中匯出的但未被使用的其他 hooks 會被tree shaking,第一次使用這個庫的時候我很好奇,為什麼沒有按需引入的使用方式,結果打包分析時我傻了,原來人家天生支援按需引入。

可能常用的antd以及lodash都要配一配,導致產生了慣性思維。

回到正題。如果將樣式使用javascript來編寫,在某種維度上講,元件庫和工具庫一致了,配好sideEffects,自動按需引入,美滋滋。

而且每個元件都與自己的樣式繫結,不需要業務方或元件開發者去維護樣式依賴,什麼是樣式依賴,後面會講到。

缺點:

  1. 樣式無法單獨快取;
  2. styled-components 自身體積較大;
  3. 複寫元件樣式需要使用屬性選擇器或者使用styled-components,麻煩了點。

需要看取捨了,偷偷說一句styled-components做主題定製也極其方便。

方案 3 是antd使用的這種方案。

在搭建元件庫的過程中,有一個問題困擾了我很久:為什麼需要alert/style/index.js引入less檔案或alert/style/css.js引入css檔案?

答案是管理樣式依賴

因為我們的元件是沒有引入樣式檔案的,需要使用者去手動引入。

假設存在以下場景:引入<Button /><Button />依賴了<Icon />,使用者需要手動去引入呼叫的元件的樣式(<Button />)及其依賴的元件樣式(<Icon />),遇到複雜元件極其麻煩,所以元件庫開發者可以提供一份這樣的js檔案,使用者手動引入這個js檔案,就能引入對應元件及其依賴元件的樣式。

那麼問題又來了,為什麼元件不能自己去import './index.less'呢?

可以,不過業務方要配置less-loader,什麼,業務方不想配,要你import './index.css'??

可以,業務方爽了,元件開發方不爽。

所以我們要找一個大家都爽的方案:

  1. 開發方能夠開心的使用前處理器;
  2. 業務方不需要額外的使用成本。

答案就是css in js單獨提供一份style/css.js檔案,引入的是元件 css樣式檔案依賴,而非 less 依賴,元件庫底層抹平差異。

之前瞭解到father可以在打包的時候將index.less轉成index.css,這倒是個好法子,但是一些重複引入的樣式模組(比如動畫樣式),會被重複打包,不知道有沒有好的解決方案。

生成 css 檔案

安裝相關依賴。

yarn add gulp-less gulp-autoprefixer gulp-cssnano --dev

less檔案生成對應的css檔案,在gulpfile.js中增加less2css任務。

// ...

/**
 * 生成css檔案
 */
function less2css() {
  return gulp
    .src(paths.styles)
    .pipe(less()) // 處理less檔案
    .pipe(autoprefixer()) // 根據browserslistrc增加字首
    .pipe(cssnano({ zindex: false, reduceIdents: false })) // 壓縮
    .pipe(gulp.dest(paths.dest.lib))
    .pipe(gulp.dest(paths.dest.esm));
}

const build = gulp.parallel(buildScripts, copyLess, less2css);

// ...

執行yarn build,元件style目錄下已經存在css檔案了。

接下來我們需要一個alert/style/css.js來幫使用者引入css檔案。

生成 css.js

此處參考antd-tools的實現方式:在處理scripts任務中,截住style/index.js,生成style/css.js,並通過正則將引入的less檔案字尾改成css

安裝相關依賴。

yarn add through2 --dev

gulpfile.js

// ...

/**
 * 編譯指令碼檔案
 * @param {*} babelEnv babel環境變數
 * @param {*} destDir 目標目錄
 */
function compileScripts(babelEnv, destDir) {
  const { scripts } = paths;
  process.env.BABEL_ENV = babelEnv;
  return gulp
    .src(scripts)
    .pipe(babel()) // 使用gulp-babel處理
    .pipe(
      through2.obj(function z(file, encoding, next) {
        this.push(file.clone());
        // 找到目標
        if (file.path.match(/(\/|\\)style(\/|\\)index\.js/)) {
          const content = file.contents.toString(encoding);
          file.contents = Buffer.from(cssInjection(content)); // 檔案內容處理
          file.path = file.path.replace(/index\.js/, 'css.js'); // 檔案重新命名
          this.push(file); // 新增該檔案
          next();
        } else {
          next();
        }
      }),
    )
    .pipe(gulp.dest(destDir));
}

// ...

cssInjection的實現:

gulpfile.js

/**
 * 當前元件樣式 import './index.less' => import './index.css'
 * 依賴的其他元件樣式 import '../test-comp/style' => import '../test-comp/style/css.js'
 * 依賴的其他元件樣式 import '../test-comp/style/index.js' => import '../test-comp/style/css.js'
 * @param {string} content
 */
function cssInjection(content) {
  return content
    .replace(/\/style\/?'/g, "/style/css'")
    .replace(/\/style\/?"/g, '/style/css"')
    .replace(/\.less/g, '.css');
}

再進行打包,可以看見元件style目錄下生成了css.js檔案,引入的也是上一步less轉換而來的css檔案。

lib/alert

├── alert.js
├── index.js
├── interface.js
└── style
    ├── css.js # 引入index.css
    ├── index.css
    ├── index.js
    └── index.less

按需載入

在 package.json 中增加sideEffects屬性,配合ES module達到tree shaking效果(將樣式依賴檔案標註為side effects,避免被誤刪除)。

// ...
"sideEffects": [
  "dist/*",
  "esm/**/style/*",
  "lib/**/style/*",
  "*.less"
],
// ...

使用以下方式引入,可以做到js部分的按需載入,但需要手動引入樣式:

import { Alert } from 'happy-ui';
import 'happy-ui/esm/alert/style';

也可以使用以下方式引入:

import Alert from 'happy-ui/esm/alert'; // or import Alert from 'happy-ui/lib/alert';
import 'happy-ui/esm/alert/style'; // or import Alert from 'happy-ui/lib/alert';

以上引入樣式檔案的方式不太優雅,直接入口處引入全量樣式檔案又和按需載入的本意相去甚遠。

使用者可以藉助babel-plugin-import來進行輔助,減少程式碼編寫量(說好的不加入其他使用成本的呢~)。

import { Alert } from 'happy-ui';

⬇️

import Alert from 'happy-ui/lib/alert';
import 'happy-ui/lib/alert/style';

生成 umd

沒用上,這一塊標記為 todo 吧。

本節程式碼可以在倉庫chapter-3分支獲取,若存在與本文內容不符的地方,以master分支以及文章為準。

元件測試

與軟體操作行為越接近的測試,越能給予你信心。

本節主要講述如何在元件庫中引入jest以及@testing-library/react,而不會深入單元測試的學習。

如果你對下列問題感興趣:

  1. What-單元測試是什麼?
  2. Why-為什麼要寫單元測試?
  3. How-編寫單元測試的最佳實踐?

那麼可以看看以下文章:

相關配置

安裝依賴:

yarn add jest ts-jest @testing-library/react @testing-library/jest-dom identity-obj-proxy @types/jest @types/testing-library__react --dev
  • jest: JavaScript 測試框架,專注於簡潔明快;
  • ts-jest:為TypeScript編寫jest測試用例提供支援;
  • @testing-library/react:簡單而完整的React DOM測試工具,鼓勵良好的測試實踐;
  • @testing-library/jest-dom:自定義的jest匹配器(matchers),用於測試DOM的狀態(即為jestexcept方法返回值增加更多專注於DOMmatchers);
  • identity-obj-proxy:一個工具庫,此處用來mock樣式檔案。

新建jest.config.js,並寫入相關配置,更多配置可參考jest 官方文件-配置,只看幾個常用的就可以。

jest.config.js

module.exports = {
  verbose: true,
  roots: ['<rootDir>/components'],
  moduleNameMapper: {
    '\\.(css|less|scss)$': 'identity-obj-proxy',
    '^components$': '<rootDir>/components/index.tsx',
    '^components(.*)$': '<rootDir>/components/$1',
  },
  testRegex: '(/test/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  testPathIgnorePatterns: ['/node_modules/', '/lib/', '/esm/', '/dist/'],
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};

修改package.json,增加測試相關命令,並且程式碼提交前,跑測試用例,如下:

package.json

"scripts": {
  ...
+  "test": "jest",                         # 執行jest
+  "test:watch": "jest --watch",           # watch模式下執行
+  "test:coverage": "jest --coverage",     # 生成測試覆蓋率報告
+  "test:update": "jest --updateSnapshot"  # 更新快照
},
...
"lint-staged": {
  "components/**/*.ts?(x)": [
    "prettier --write",
    "eslint --fix",
+   "jest --bail --findRelatedTests",
    "git add"
  ],
  ...
}

修改gulpfile.js以及tsconfig.json,避免打包時,把測試檔案一併處理了。

gulpfile.js

const paths = {
  ...
- scripts: ['components/**/*.{ts,tsx}', '!components/**/demo/*.{ts,tsx}'],
+ scripts: [
+   'components/**/*.{ts,tsx}',
+   '!components/**/demo/*.{ts,tsx}',
+   '!components/**/__tests__/*.{ts,tsx}',
+ ],
};

tsconfig.json

{
- "exclude": ["components/**/demo"]
+ "exclude": ["components/**/demo", "components/**/__tests__"]
}

編寫測試用例

<Alert />比較簡單,此處只作示例用,簡單進行一下快照測試。

在對應元件的資料夾下新建__tests__資料夾,用於存放測試檔案,其內新建index.test.tsx檔案,寫入以下測試用例:

components/alert/tests/index.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import Alert from '../alert';

describe('<Alert />', () => {
  test('should render default', () => {
    const { container } = render(<Alert>default</Alert>);
    expect(container).toMatchSnapshot();
  });

  test('should render alert with type', () => {
    const kinds: any[] = ['info', 'warning', 'positive', 'negative'];

    const { getByText } = render(
      <>
        {kinds.map(k => (
          <Alert kind={k} key={k}>
            {k}
          </Alert>
        ))}
      </>,
    );

    kinds.forEach(k => {
      expect(getByText(k)).toMatchSnapshot();
    });
  });
});

更新一下快照:

yarn test:update

可以看見同級目錄下新增了一個__snapshots__資料夾,裡面存放對應測試用例的快照檔案。

生成的快照檔案

再執行測試用例:

yarn test

通過測試用例

可以發現我們通過了測試用例。。。額,這裡當然能通過,主要是後續我們進行迭代重構時,都會重新執行測試用例,與最近的一次快照進行比對,如果與快照不一致(結構發生了改變),那麼相應的測試用例就無法通過。

對於快照測試,褒貶不一,這個例子也著實簡單得很,甚至連擴充套件的 jest-dom提供的 matchers 都沒用上。

如何編寫優秀的測試用例,我也是一個新手,只能說多看多寫多嘗試,前面推薦的文章很不錯。

本節程式碼可以在倉庫chapter-4分支獲取,若存在與本文內容不符的地方,以master分支以及文章為準。

標準化釋出流程

本節主要是講解如何通過一行命令完成以下六點內容:

  1. 版本更新
  2. 生成 CHANGELOG
  3. 推送至 git 倉庫
  4. 元件庫打包
  5. 釋出至 npm
  6. 打 tag 並推送至 git

如果你不想程式碼,很好,用np(如果我一開始就知道這個工具,我也不會去寫程式碼,我真傻,真的)。

package.json

"scripts": {
+ "release": "ts-node ./scripts/release.ts"
},

直接甩程式碼吧,實在不復雜。

/* eslint-disable  import/no-extraneous-dependencies,@typescript-eslint/camelcase, no-console */
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';
import child_process from 'child_process';
import util from 'util';
import chalk from 'chalk';
import semverInc from 'semver/functions/inc';
import { ReleaseType } from 'semver';

import pkg from '../package.json';

const exec = util.promisify(child_process.exec);

const run = async (command: string) => {
  console.log(chalk.green(command));
  await exec(command);
};

const currentVersion = pkg.version;

const getNextVersions = (): { [key in ReleaseType]: string | null } => ({
  major: semverInc(currentVersion, 'major'),
  minor: semverInc(currentVersion, 'minor'),
  patch: semverInc(currentVersion, 'patch'),
  premajor: semverInc(currentVersion, 'premajor'),
  preminor: semverInc(currentVersion, 'preminor'),
  prepatch: semverInc(currentVersion, 'prepatch'),
  prerelease: semverInc(currentVersion, 'prerelease'),
});

const timeLog = (logInfo: string, type: 'start' | 'end') => {
  let info = '';
  if (type === 'start') {
    info = `=> 開始任務:${logInfo}`;
  } else {
    info = `✨ 結束任務:${logInfo}`;
  }
  const nowDate = new Date();
  console.log(
    `[${nowDate.toLocaleString()}.${nowDate
      .getMilliseconds()
      .toString()
      .padStart(3, '0')}] ${info}
    `,
  );
};

/**
 * 獲取下一次版本號
 */
async function prompt(): Promise<string> {
  const nextVersions = getNextVersions();
  const { nextVersion } = await inquirer.prompt([
    {
      type: 'list',
      name: 'nextVersion',
      message: `請選擇將要釋出的版本 (當前版本 ${currentVersion})`,
      choices: (Object.keys(nextVersions) as Array<ReleaseType>).map(level => ({
        name: `${level} => ${nextVersions[level]}`,
        value: nextVersions[level],
      })),
    },
  ]);
  return nextVersion;
}

/**
 * 更新版本號
 * @param nextVersion 新版本號
 */
async function updateVersion(nextVersion: string) {
  pkg.version = nextVersion;
  timeLog('修改package.json版本號', 'start');
  await fs.writeFileSync(path.resolve(__dirname, './../package.json'), JSON.stringify(pkg));
  await run('npx prettier package.json --write');
  timeLog('修改package.json版本號', 'end');
}

async function generateChangelog() {
  timeLog('生成CHANGELOG.md', 'start');
  await run(' npx conventional-changelog -p angular -i CHANGELOG.md -s -r 0');
  timeLog('生成CHANGELOG.md', 'end');
}

/**
 * 將程式碼提交至git
 */
async function push(nextVersion: string) {
  timeLog('推送程式碼至git倉庫', 'start');
  await run('git add package.json CHANGELOG.md');
  await run(`git commit -m "v${nextVersion}" -n`);
  await run('git push');
  timeLog('推送程式碼至git倉庫', 'end');
}

/**
 * 元件庫打包
 */
async function build() {
  timeLog('元件庫打包', 'start');
  await run('npm run build');
  timeLog('元件庫打包', 'end');
}

/**
 * 釋出至npm
 */
async function publish() {
  timeLog('釋出元件庫', 'start');
  await run('npm publish');
  timeLog('釋出元件庫', 'end');
}

/**
 * 打tag提交至git
 */
async function tag(nextVersion: string) {
  timeLog('打tag並推送至git', 'start');
  await run(`git tag v${nextVersion}`);
  await run(`git push origin tag v${nextVersion}`);
  timeLog('打tag並推送至git', 'end');
}

async function main() {
  try {
    const nextVersion = await prompt();
    const startTime = Date.now();
    // =================== 更新版本號 ===================
    await updateVersion(nextVersion);
    // =================== 更新changelog ===================
    await generateChangelog();
    // =================== 程式碼推送git倉庫 ===================
    await push(nextVersion);
    // =================== 元件庫打包 ===================
    await build();
    // =================== 釋出至npm ===================
    await publish();
    // =================== 打tag並推送至git ===================
    await tag(nextVersion);
    console.log(`✨ 釋出流程結束 共耗時${((Date.now() - startTime) / 1000).toFixed(3)}s`);
  } catch (error) {
    console.log('? 釋出失敗,失敗原因:', error);
  }
}

main();

初始化元件

每次初始化一個元件就要新建許多檔案以及資料夾,複製貼上也可,不過還可以使用更高階一點的偷懶方式。

常規思路,新建一個元件模板資料夾,裡面包含一個元件所需要的所有檔案,同時寫好檔案內容。

至於一些動態內容,譬如元件中英文名稱,選一個你喜歡的模板語言(如 handlebars),用其方式留空{{componentName}}

package.json

"scripts": {
+ "new": "ts-node ./scripts/new.ts"
},

接下來我們在new.ts中編寫相關步驟,無非是:

  1. 基於inquirer.js詢問一些基本元件資訊
  2. 結合資訊,渲染模板(填空)至元件資料夾
  3. 向 components/index.ts 插入匯出語句

你以為我會寫new.ts嗎,不,我不會(雖然我真寫過)。

主要是使用metalsmith進行資料與模板結合,寫腳手架的同學可能比較熟悉。

自從我知道了plop.js這個庫,那麼又可以偷懶了(為什麼之前沒有人告訴我有這麼多好用的工具???)

"scripts": {
- "new": "ts-node ./scripts/new.ts",
+ "new": "plop --plopfile ./scripts/plopfile.ts",
},

於是上述流程可以大大簡化,不需要寫程式碼去詢問,不需要手動渲染模板,我們要做的就是寫好模板,並且配置好問題以及渲染目的地。

詳情可見:

結語

文章很長,也是我個人學習中的總結,如果本文幫助到了你請給倉庫一顆 ✨✨ 和本文一個贊。

如果有錯誤煩請在評論區指正交流,謝謝。

倉庫地址

相關文章