痛点
相信每个人在项目开发的时候,都会遇到一个很矛盾的问题! 自己开发的公共组件不想写readme文档,在用别人开发的组件时又见不得它没有说明文档。
维护了api文档的组件,在修改时又需要额外的精力去保持api文档的实时性
调研
不想写文档那就自己生成文档 在调研了市面上的一些组件文档生成工具, Storybook、 react-react-styleguidist算是做的比较好的。
工具选择
一开始是用babel写一版的,然后发现babel很难解析出依赖的props类型,对于注释的解析市面上也有通用的jsdoc 参考styleguidist开源的react-docgen-typescript库,最终选择了react-docgen-typescript库作为解析器。并且加上了tsdoc来增强解析注释的能力。
原理
- 通过解析得到代码的AST
- 通过AST判断导出的Class/Function是否是React组件
- 提取出组件的props和jsdoc规范的注释
- 形成基本的api文档
生成
import classNames from 'classnames';
import React from 'react';
import { MyButtonType } from './helper';
import './index.less';
/**
* 通用按钮组件
* @example <MyButton>按钮</MyButton>
* @example <MyButton disabled>按钮</MyButton>
*/
const MyButton = ({
disabled = false,
size = 'middle',
type = 'default',
fill = 'solid',
onClick = null,
children,
className,
}: MyButtonType) => {
return (
<div
onClick={disabled ? null : onClick}
styleName={classNames('button', {
[size]: size,
[type]: type,
[fill]: fill,
disable: disabled ? 'disable' : null,
})}
className={className}
>
{children}
</div>
);
};
export default MyButton;
# Button
通用按钮组件
## 示例
`\`\`jsx
<MyButton>按钮</MyButton>
<MyButton disabled>按钮</MyButton>
`\`\`
## Props
| 属性 | 说明 | 类型 | 默认值 |
| ---- | ----------- | ---- | ------- |
| type | 类型 | "primary" \| "default" \| "gray" | default |
| fill | 填充 | "solid" \| "outline" \| "none" | solid |
| size | 尺寸 | "mini" \| "small" \| "middle" \| "large" | middle |
| className | 样式类 | string | |
| disabled | 禁用 | boolean | false |
| children | 插槽 | React.ReactNode | |
| onClick | 点击回调 | () => void | null |
tip
react-docgen-typescript使用时会有几个问题
1.必须使用import * as React from 'react'; 不然解析不出是否是react组件
2.需要安装@types/react
项目使用
附上项目地址,使用方法在项目的readme中有详细说明 react-docgen-component