> For AI agents: the complete documentation index is available at https://rspress.rs/zh/llms.txt, the full documentation bundle is available at https://rspress.rs/zh/llms-full.txt.

# @rspress/plugin-api-docgen 

[源码](https://github.com/web-infra-dev/rspress/tree/main/packages/plugin-api-docgen)

用于自动生成 API 文档描述，支持 [react-docgen-typescript](https://github.com/styleguidist/react-docgen-typescript) 和 [documentation](https://github.com/documentationjs/documentation)。

## 安装


```sh [npm]
npm add @rspress/plugin-api-docgen -D
```

```sh [yarn]
yarn add @rspress/plugin-api-docgen -D
```

```sh [pnpm]
pnpm add @rspress/plugin-api-docgen -D
```

```sh [bun]
bun add @rspress/plugin-api-docgen -D
```

```sh [deno]
deno add npm:@rspress/plugin-api-docgen -D
```

## 使用

首先在配置文件中写入以下的配置：

```ts
// rspress.config.ts
import path from 'path';
import { defineConfig } from '@rspress/core';
import { pluginApiDocgen } from '@rspress/plugin-api-docgen';

export default defineConfig({
  plugins: [
    pluginApiDocgen({
      entries: {
        button: './src/index.ts',
      },
      apiParseTool: 'react-docgen-typescript',
    }),
  ],
});
```

然后你可以在 MDX 中使用 API 组件将 API 内容注入到文档中：

```mdx
## API

这是 API 表格

<API moduleName="button" />
```

## 配置

这个插件接受一个对象参数，类型如下:

```ts
interface Options {
  entries?: Record<string, string>;
  apiParseTool?: 'react-docgen-typescript' | 'documentation';
  appDir?: string;
  parseToolOptions?: ParseToolOptions;
}
```

### appDir

`appDir`用来配置插件解析文件的基准目录，默认为 `process.cwd()`

### entries

`entries` 用来配置解析文件的基本信息：

- key 为标识符，作为 API 组件的 `moduleName`属性
- value 为解析文件的相对路径

### apiParseTool

`apiParseTool` 用来选择解析工具，默认为`react-docgen-typescript`：

- `react-docgen-typescript`针对于组件库场景，仅会解析 props 生成表格。

```tsx
export type ButtonProps = {
  /**
   * Whether to disable the button
   */
  disabled?: boolean;
  /**
   * Type of Button
   * @default 'default'
   */
  size?: 'mini' | 'small' | 'default' | 'large';
};
export const Button = (props?: ButtonProps) => {};
```

上面是一个标准写法，其中 `ButtonProps` 将被提取至表格中， `Button` 作为表格的标题。
如果使用默认导出，文件名将作为表格标题。

需要注意的是，export 导出事先定义的特性将不会被解析。

```javascript
const A = () => {};

export { A }; // wrong
export default A; // wrong
export const B = () => {}; // right
export default () => {}; // right
```

生成的内容如下：

```mdx
### ButtonTest

|   属性   |             说明              |                    类型                     |   默认值    |
| :------: | :---------------------------: | :-----------------------------------------: | :---------: |
| disabled | Whether to disable the button |                  `boolean`                  |     `-`     |
|   size   |        Type of Button         | `"mini" \| "small" \| "default" \| "large"` | `'default'` |
```

:::warning
如果 Props 里使用了 React 的类型，你需要在 tsconfig.json 里添加 types ，否则会解析不到 React 命名空间下的类型。

```json
{
  "compilerOptions": {
    "types": ["react"]
  }
}
```

更好的方式是直接引用类型，例如

```tsx
import { FC } from 'react';
```

:::

- `documentation`适用于工具库场景，用来解析 JSDoc 注释。
  下面是一个带有 JSDoc 注释的 greet 函数。

```ts
/**
 * Greet function that returns a greeting message.
 * @param {string} name - The name of the person to greet.
 * @param {string} [greeting='Hello'] - The greeting to use.
 * @returns {string} The greeting message.
 */
function greet(name: string, greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}
```

上面是一个带有 JSDoc 注释的 greet 函数。生成的内容如下：

```md
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## greet

Greet function that returns a greeting message.

### Parameters

- `name` **[string][1]** The name of the person to greet.
- `greeting` **[string][1]** The greeting to use. (optional, default `'Hello'`)

Returns **[string][1]** The greeting message.

[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
```

### parseToolOptions

`parseToolOptions` 用来传入对应解析器的参数，其类型如下：

```ts
type ParseToolOptions = {
  'react-docgen-typescript'?: ParserOptions & {
    tsconfigPath?: Record<string, string>;
    compilerOptions?: Record<string, ts.CompilerOptions>;
  };
  documentation?: DocumentationArgs;
};
```

请参考 [ParserOptions](https://github.com/styleguidist/react-docgen-typescript/blob/b7ea0a235efb7c78a1158ca12d864de2bc2ee30e/src/parser.ts#L84-L95) 和 [DocumentationArgs](https://github.com/documentationjs/documentation/blob/master/docs/NODE_API.md#parameters-1) 了解可用选项。

如果解析器是 `react-docgen-typescript`，默认使用 `withDefaultConfig` 方法创建解析器实例，如果配置了 `tsconfigPath` 或 `compilerOptions` 则会分别使用 `withCompilerOptions` 和 `withCustomConfig` 方法创建解析器实例，`tsconfigPath` 和 `compilerOptions`可以分别针对每个 `entry` 设置，详情查看 [Custom Parsers](https://github.com/styleguidist/react-docgen-typescript/blob/b7ea0a235efb7c78a1158ca12d864de2bc2ee30e/README.md#usage)。
