跳至內容
Fumadocs

Rehype Code

程式碼語法突顯器

Fumadocs 所使用的語法突顯器,為 @shikijs/rehype 的包裝。

它會將原始的 <pre /> 程式碼區塊轉換成已語法突顯的程式碼區塊:

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

使用方式

Rehype Code 是一個 rehype 外掛,Fumadocs MDX 預設會啟用它。您可以透過 rehypeCodeOptions 傳入選項:

source.config.ts
import { defineConfig } from 'fumadocs-mdx/config';

export default defineConfig({
  mdxOptions: {
    rehypeCodeOptions: {
      themes: {
        light: 'github-light',
        dark: 'github-dark',
      },
    },
  },
});

語法突顯器

此外掛使用 Shiki。rehypeCodeFromHighlighter 則可改用其他語法突顯器 (例如 Highlights) ,並接受 Shiki 以外的選項。請傳入一個函式,搭配此外掛的 transformer 建立語法突顯器。

請停用預設外掛,再加入此外掛:

source.config.ts
import { defineConfig } from 'fumadocs-mdx/config';
import { rehypeCodeFromHighlighter } from 'fumadocs-core/mdx-plugins/rehype-code.core';
import { highlighter } from './lib/highlighter';

export default defineConfig({
  mdxOptions: {
    rehypeCodeOptions: false,
    rehypePlugins: [
      () =>
        rehypeCodeFromHighlighter(({ transformers }) =>
          highlighter.override({ shikiTransformers: transformers }),
        ),
    ],
  },
});

Meta

它會解析 title meta 字串,並以屬性的形式加到 pre 元素上。

```js title="Title"
console.log('Hello');
```

您可以透過 filterMetaString 選項,在處理 meta 字串之前先進行過濾。

行內程式碼

您可以透過 inline 選項啟用此功能:

import { type RehypeCodeOptions } from 'fumadocs-core/mdx-plugins';

const rehypeCodeOptions: RehypeCodeOptions = {
  inline: 'tailing-curly-colon',
};
Syntax
這是經過語法突顯的行內程式碼: `console.log("hello world"){:js}`.

這是一段經過語法突顯的行內程式碼:console.log("hello world")。

圖示

此外掛會根據語言的 meta 字串,自動加入 icon 屬性。 其值為 HTML 字串,您可以透過 React 的 dangerouslySetInnerHTML 加以算繪。

```ts
console.log('This should shows the logo of TypeScript');
```

您可以透過 icon 選項停用或自訂圖示。

更多選項

這些選項繼承自 Shiki,其他選項請參閱 Shiki 的說明文件。

How is this guide?

最後更新於