Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何自动生成 API or Props 文档 #436

Closed
ReAlign opened this issue Jan 12, 2023 · 2 comments
Closed

如何自动生成 API or Props 文档 #436

ReAlign opened this issue Jan 12, 2023 · 2 comments
Assignees

Comments

@ReAlign
Copy link

ReAlign commented Jan 12, 2023

如题

@luhc228 luhc228 self-assigned this Feb 2, 2023
@luhc228 luhc228 added the urgent label Mar 13, 2023
@luhc228
Copy link
Member

luhc228 commented Mar 24, 2023

自动生成 React 组件文档

方案调研

react-docgen 和 react-docgen-typescript 是能解析 react 组件的 Props 描述、类型等等信息:

react-docgen react-docgen-typescript
JSX + Class Component + propTypes
JSX + Function Component + propTypes
TSX + Class Component ❌(props 的类型没解析出来)
TSX + Function Component
支持导出多个组件

使用 react-docgen 去解析以下的 tsx 文件内容:

import React from 'react';

interface Props {
  /**
   * I am description
   * @default 'aaa'
   *
   */
  foo: string;

  bar: string | number | boolean;
}

/**
 * Hi I am CComponent
 */
export function CComponent(props: Props) {
  console.log(props);
  return (
    <div>xxx</div>
  )
}

CComponent.defaultProps = {
  foo: 'foo',
  // bar: 'bar',
}

得到的结果如以下所示:

{
  description: 'Hi I am CComponent',
  displayName: 'CComponent',
  methods: [],
  props: {
    foo: {
      required: false,
      flowType: { name: 'string' },
      description: "I am description\n@default 'aaa'\n@t",
      defaultValue: { value: "'foo'", computed: false }
    },
    bar: {
      required: true,
      flowType: {
        name: 'union',
        raw: 'string | number | boolean',
        elements: [ { name: 'string' }, { name: 'number' }, { name: 'boolean' } ]
      },
      description: 'xx'
    }
  }
} 

不过 react-docgen 暂时不支持 JSDoc 的解析:Generate docs for hooks · Issue #332 · reactjs/react-docgen (github.com),但是目前来看能力能满足大部分场景需求了。

对于 Node 库来说一般会使用 JSDoc 的方式编写函数/类的描述信息,可以使用 [typedoc](Installation | TypeDoc) 生成文档。这个后续再支持

参考:

使用方式

通过写 <ReactDocgenAPI path="xxxx"></ReactDocgenAPI> 作为 React 组件文档的占位:
比如:

<!-- docs/header.md -->
---
title: 我是 Header 组件
---

## 属性

<ReactDocgenAPI path="../src/Header.tsx"></ReactDocgenAPI>

最终渲染生成的 markdown 内容是:

## 属性

| 参数名 | 描述 |   类型   | 默认值 |
| ------ | :--: | :------: | :-----: |
| title  | 标题 | `string` |    `-` |

两个约定的地方:

  1. 约定每个文件只能导出一个组件,否则无法正常生成组件的文档。
  2. 无法解析从其他模块中导入的 ts 类型

@luhc228
Copy link
Member

luhc228 commented Mar 28, 2023

讨论的结果是,尽量不要把组件文档的逻辑耦合到 @ice/pkg-plugin-docusaurus 中。

新的解决方案是:
新建一个 remark 插件(remark-react-docgen-docusaurus),然后在 @ice/pkg-plugin-docusaurus 支持新增 remark 插件。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants