跳至內容
Fumadocs

Auto Type Table

自動產生的型別表格

屬性

型別

僅限伺服器元件

此元件無法在用戶端元件中使用,請改用建置時期的 MDX 整合。

此元件會根據 TypeScript 定義,為您的文件產生表格。

使用方式

npm i fumadocs-typescript

初始化 TypeScript 編譯器,並將它加入為 MDX 元件。

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

const generator = createGenerator({
  // 設定快取,在 Vercel 等無伺服器(serverless)平台上必須設定
  cache: createFileSystemGeneratorCache('.next/fumadocs-typescript'),
});

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

現在您可以在 MDX 內容中使用 <AutoTypeTable />。

更多用法請參閱 TypeScript DocGen。

從檔案

此元件接受 path prop,用來指向 TypeScript 檔案,並以 name 指定要使用的匯出型別名稱。

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

此路徑是相對於您的專案目錄 (cwd) 。由於 AutoTypeTable 是 React 伺服器元件,因此無法存取 MDX 檔案路徑等建置時期的資訊。

從型別產生

您可以直接指定要產生的型別,不需要實際的 TypeScript 檔案。

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

若有提供 path,它會與該 TypeScript 檔案共用相同的上下文。

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

當 type 有多行時,必須加上 export 陳述式並提供 name prop。

content.mdx
<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 Compiler API 擷取型別資訊,並會載入目前工作目錄中的 tsconfig.json 檔案。

您可以透過 createGenerator() 變更編譯器設定。

import { createGenerator, createFileSystemGeneratorCache } from 'fumadocs-typescript';

const generator = createGenerator({
  tsconfigPath: './tsconfig.json',
  // 解析相對路徑時的基準目錄(通常為 cwd)
  basePath: './',
  // 其他選項……
});

檔案系統

由於它依賴檔案系統,引用此元件的頁面必須在建置階段產生。在 serverless 執行階段算繪此元件可能會發生問題。

參考資料

屬性

型別

How is this guide?

最後更新於