Fumadocs

自动类型表格

自动生成的类型表格

Prop

Type

仅限服务器组件

您不能在客户端组件中使用此组件。

它基于 TypeScript 定义为您的文档生成表格。

用法

npm i fumadocs-typescript

初始化 TypeScript 编译器并将其添加为 MDX 组件。

mdx-components.tsx
import defaultComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
import { createGenerator } from 'fumadocs-typescript';
import { AutoTypeTable } from 'fumadocs-typescript/ui';

const generator = createGenerator();

export function getMDXComponents(components?: MDXComponents): MDXComponents {
  return {
    ...defaultComponents,
    AutoTypeTable: (props) => (
      <AutoTypeTable {...props} generator={generator} />
    ),
    ...components,
  };
}

从文件

它接受一个 path 属性,该属性指向 TypeScript 文件,以及 name 用于导出的类型名称。

path/to/file.ts
export interface MyInterface {
  name: string;
}
<AutoTypeTable path="./path/to/file.ts" name="MyInterface" />

路径相对于您的项目目录(cwd),因为 AutoTypeTable 是一个 React 服务器组件,它无法访问构建时信息,如 MDX 文件路径。

从类型

您可以指定要生成的类型,而无需实际的 TypeScript 文件。

import { AutoTypeTable } from 'fumadocs-typescript/ui';

<AutoTypeTable type="{ hello: string }" />

当提供 path 时,它与 TypeScript 文件共享相同的上下文。

file.ts
export type A = { hello: string };
<AutoTypeTable path="file.ts" type="A & { world: string }" />

type 有多个行时,需要导出语句和 name 属性。

<AutoTypeTable
  path="file.ts"
  name="B"
  type={`
import { ReactNode } from "react"
export type B = ReactNode | { world: string }
`}
/>

函数

请注意,仅允许对象类型。对于函数,您应该将它们包装成对象。

export interface MyInterface {
  myFn: (input: string) => void;
}

TypeScript 编译器

在底层,它使用 TypeScript 编译器 API 来提取类型信息。 当前工作目录中的 tsconfig.json 文件将被加载。

您可以从 createGenerator() 更改编译器设置。

import { createGenerator } from 'fumadocs-typescript';

const generator = createGenerator({
  tsconfigPath: './tsconfig.json',
  // 用于解析相对路径的位置(通常为 cwd)
  basePath: './',
  // 禁用文件系统缓存
  cache: false,
});

文件系统

它依赖于文件系统,因此,引用此组件的页面必须在 构建时 构建。在无服务器运行时渲染组件可能会导致问题。

引用

Prop

Type

How is this guide?

Last updated on