React组件库搭建流程 (一) -- 开发调试

1,036 阅读3分钟

前言

组件库对前端们而言并不陌生,主要是为了提高开发效率,避免重复造轮子。当下而言前端组件库百花齐放,antd、element ui这些基础组件库已经很强大,使用于各种业务场景。本文主旨是让同学们能快速的搭建起组件库的基础平台,包括文档、部署站点等。站点是基于dumi生成,有兴趣的同学可以深入学习。

初始化

新建一个WJ-UI文件夹,并执行npm init 初始化。

mkdir WJ-UI
cd WJ-UI
npm init --y

TypeScript ts的优点同学们都懂,这边增加ts依赖,并新建tsconfig.json

yarn add typescript --dev

创建全局依赖的同学,可以用tsc --init生成tsconfig.json, 修改成以下内容。

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "esnext",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "jsx": "react",                                /* Specify what JSX code is generated. */
    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
     "resolveJsonModule": true,                        /* Enable importing .json files */
    /* Emit */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationDir": "./lib",                           /* Specify the output directory for generated declaration files. */
    "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

dumi

因为我们需要快速搭建上搜,此处加入 dumi 作为文档站点工具,并兼顾开发调试功能。

yarn add dumi serve --dev

在package.json,在 scripts中加入以下代码。

"scripts": {
  "dev": "dumi dev", // 启动开发环境 
  "build": "rimraf site && dumi build", // 构建站点 
  "preview": "npm run build && serve site" // 本地预览构建后的站点
},

新建.umirc.ts配置文件,写入以下内容:

import { defineConfig } from 'dumi';

const repo = 'WU-UI';

export default defineConfig({
  title: repo,
  outputPath: 'docs-dist',
  mode: 'site',
  hash: true,
  // Because of using GitHub Pages
  base: `/${repo}/`,
  publicPath: `/${repo}/`,
});

可以参考 # dumi-template, 取出自己需要的配置,当然还有很多配置,需要的同学可以自行前往官网查看。

docs 在根目录下新建docs文件夹,包含除组件外的其他文档,如首页文档等。例 index.md:

---
title: WJ UI
hero:
  title: WJ UI
  desc: 好用的UI库
  actions:
    - text: 快速上手
      link: /button
features:
  - icon: https://gw.alipayobjects.com/zos/bmw-prod/881dc458-f20b-407b-947a-95104b5ec82b/k79dm8ih_w144_h144.png
    title: 自学用
    desc: 自学用
  - icon: https://gw.alipayobjects.com/zos/bmw-prod/d60657df-0822-4631-9d7c-e7a869c2f21c/k79dmz3q_w126_h126.png
    title: 自学用
    desc: 自学用
footer: Copyright © 2021
---

image.png 还有很多配置,需要的同学请自行查看官网,这里就做个示例。

开发组件并调试

接下来就是组件的开发,这里开大家打个样,只是个例子:

Button
    ├── index.tsx          
    └── style
        ├── index.less     
        └── index.ts        

src/Button/index.tsx

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

export interface ButtonProps {
    /**
   * 可以这样写属性描述
   * @description       设置按钮类型	
   * @description.zh-CN 还支持不同的 locale 后缀来实现多语言描述
   * @default           支持定义默认值
   */
    type?: 'primary' | 'dashed' | 'text' | 'link'
}

const prefixCls = 'wj-button';

const Button:React.FC<ButtonProps> = ({children, type = 'primary', ...rest }) => {
    return <div className={prefixCls}
        style = {{}}>
        {children}
    </div>
}


Button.propTypes = {
    type: t.oneOf(['primary', 'dashed', 'text', 'link']),
  };

export default Button;

src/index.ts

export { default as Button } from './Button';

以上是按钮组件例子,组件的具体内容需要同学们自行填充,这里主要演示搭建流程。下面开始调试页面:

新建src/Button/demo/index.tsx,并引入组件。

import React from 'react';
import Button from '../index';
import '../style';

export default () => <Button>按钮</Button>;

新建src/Button/index.md,并引入组件。


---
title: Button 按钮
nav:
  title: 组件
  order: 2
group:
  title: 通用
  order: 1
---

# Button 按钮

按钮,用于开始一个即时操作。

## 代码演示

### 基本用法

<code src="./demo/index.tsx"></code>

<API></API>

image.png

大家看到这样就有一个完整的调试页面,API也一并编写好了,是因为 dumi 引用了react-docgen-typescript直接在组件的类型定义时加上注释,就能自动生成API,非常方便。 到这里初始化开发调试都完成了,下一篇我们讲解如何测试以及如何部署到Github Pages。