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, and this page is available as Markdown at https://rspress.rs/zh/plugin/official-plugins/api-docgen.md.
close

@rspress/plugin-api-docgen

用于自动生成 API 文档描述,支持 react-docgen-typescript 和 documentation。

安装

npm
yarn
pnpm
bun
deno
vlt
npm add @rspress/plugin-api-docgen -D

使用

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

// 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 内容注入到文档中:

## API

这是 API 表格

<API moduleName="button" />

国际化

该插件通过插件 API i18nSource 注入以下国际化文案:

翻译源码
i18n.ts
// cspell:disable
export const apiDocgenI18n = {
  apiDocgenProperty: {
    en: 'Property',
    zh: '属性',
    ja: 'プロパティ',
    ko: '속성',
    ru: 'Свойство',
    ta: 'பண்பு',
  },
  apiDocgenDescription: {
    en: 'Description',
    zh: '说明',
    ja: '説明',
    ko: '설명',
    ru: 'Описание',
    ta: 'விளக்கம்',
  },
  apiDocgenType: {
    en: 'Type',
    zh: '类型',
    ja: '型',
    ko: '타입',
    ru: 'Тип',
    ta: 'வகை',
  },
  apiDocgenDefaultValue: {
    en: 'Default Value',
    zh: '默认值',
    ja: 'デフォルト値',
    ko: '기본값',
    ru: 'Значение по умолчанию',
    ta: 'இயல்புநிலை மதிப்பு',
  },
  apiDocgenRequired: {
    en: 'Required',
    zh: '必填',
    ja: '必須',
    ko: '필수',
    ru: 'Обязательно',
    ta: 'கட்டாயம்',
  },
  apiDocgenClassName: {
    en: 'Additional css class',
    zh: '节点类名',
    ja: '追加の CSS クラス',
    ko: '추가 CSS 클래스',
    ru: 'Имя класса узла',
    ta: 'கூடுதல் CSS வகுப்பு',
  },
  apiDocgenStyle: {
    en: 'Additional style',
    zh: '节点样式',
    ja: '追加のスタイル',
    ko: '추가 스타일',
    ru: 'Стиль узла',
    ta: 'கூடுதல் பாணி',
  },
  apiDocgenChildren: {
    en: 'Children',
    zh: '子节点',
    ja: '子要素',
    ko: '자식 요소',
    ru: 'Дочерние элементы',
    ta: 'உள்ளடக்கம்',
  },
  apiDocgenDisabled: {
    en: 'Whether to disable ',
    zh: '是否禁用',
    ja: '無効にするかどうか',
    ko: '비활성화 여부',
    ru: 'Отключено',
    ta: 'முடக்க வேண்டுமா',
  },
};

可以通过用户配置 i18nSource 覆盖这些文案。

配置

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

type Entries = Record<string, string>;
type ToolEntries = Record<'react-docgen-typescript' | 'documentation', Entries>;

interface Options {
  entries?: Entries | ToolEntries;
  apiParseTool?: 'react-docgen-typescript' | 'documentation';
  appDir?: string;
  parseToolOptions?: ParseToolOptions;
}

appDir

  • 类型:string
  • 默认值:process.cwd()

设置解析文件时使用的基准目录。

entries

  • 类型:Entries | ToolEntries
  • 默认值:{}

配置要解析的文件。可以直接传入 Entries 映射,也可以通过 ToolEntries 为每种解析器分别提供映射。

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

apiParseTool

  • 类型:'react-docgen-typescript' | 'documentation'
  • 默认值:'react-docgen-typescript'

选择解析工具:

  • react-docgen-typescript针对于组件库场景,仅会解析 props 生成表格。
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 导出事先定义的特性将不会被解析。

const A = () => {};

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

生成的内容如下:

### ButtonTest

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

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

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

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

import { FC } from 'react';
  • documentation适用于工具库场景,用来解析 JSDoc 注释。 下面是一个带有 JSDoc 注释的 greet 函数。
/**
 * 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 函数。生成的内容如下:

<!-- 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

  • 类型:
type ParseToolOptions = {
  'react-docgen-typescript'?: ParserOptions & {
    tsconfigPath?: Record<string, string>;
    compilerOptions?: Record<string, ts.CompilerOptions>;
  };
  documentation?: DocumentationArgs;
};
  • 默认值:{}

向所选解析器传递配置。

请参考 ParserOptions 和 DocumentationArgs 了解可用选项。

如果解析器是 react-docgen-typescript,默认使用 withDefaultConfig 方法创建解析器实例,如果配置了 tsconfigPath 或 compilerOptions 则会分别使用 withCompilerOptions 和 withCustomConfig 方法创建解析器实例,tsconfigPath 和 compilerOptions可以分别针对每个 entry 设置,详情查看 Custom Parsers。