跳至內容
Fumadocs

Twoslash

在您的文件中使用 TypeScript Twoslash

使用方式

由於預設的程式碼語法突顯器 Shiki 已提供 Twoslash 整合,您只需加入一個 transformer 即可。 型別資訊由原生 TypeScript 7 編譯器負責解析,並以您專案的工作目錄為基準。

npm install fumadocs-twoslash

transformerTwoslash 是一個 Shiki transformer。請將它加入 rehype code 外掛的 transformer 中:

source.config.ts
import { defineConfig } from 'fumadocs-mdx/config';
import { transformerTwoslash } from 'fumadocs-twoslash';
import { rehypeCodeDefaultOptions } from 'fumadocs-core/mdx-plugins';

export default defineConfig({
  mdxOptions: {
    rehypeCodeOptions: {
      themes: {
        light: 'github-light',
        dark: 'github-dark',
      },
      transformers: [...(rehypeCodeDefaultOptions.transformers ?? []), transformerTwoslash()],
    },
  },
});

加入樣式。此功能需要 Tailwind CSS v4。

Tailwind CSS
@import 'fumadocs-twoslash/twoslash.css';

新增 MDX 元件。

components/mdx.tsx
import * as Twoslash from 'fumadocs-twoslash/ui'; 
import defaultComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';

export function getMDXComponents(components?: MDXComponents) {
  return {
    ...defaultComponents,
    ...Twoslash,
    ...components,
  } satisfies MDXComponents;
}

現在您可以在程式碼區塊中加上 twoslash meta 字串。

```ts twoslash
console.log('Hello World');
```

快取

您可以視需要透過 typesCache 選項啟用檔案系統快取:

source.config.ts
import {  } from 'fumadocs-twoslash';
import {  } from 'fumadocs-twoslash/cache-fs';

({
  : (),
});

範例

進一步了解 Twoslash 標記法。

.g
  • group
  • groupCollapsed
  • groupEnd
;
const player: = { : 'Hello World' };
const player: Player
('test');
const  = '123';

.();
const  = '123';

a = 132;
Cannot assign to 'a' because it is a constant.

How is this guide?

最後更新於