Rehype Code
程式碼語法突顯器
@shikijs/rehype 的封裝,而 @shikijs/rehype 正是 Fumadocs 所使用的語法突顯器。
它會將原始的 <pre /> 程式碼區塊轉換為已套用語法突顯的程式碼區塊:
```ts
console.log('Hello World');
```使用方式
Rehype Code 是一個 rehype 外掛,Fumadocs MDX 預設已啟用。您可以透過 rehypeCodeOptions 傳入選項:
import { defineConfig } from 'fumadocs-mdx/config';
export default defineConfig({
mdxOptions: {
rehypeCodeOptions: {
themes: {
light: 'github-light',
dark: 'github-dark',
},
},
},
});語法突顯器
此外掛使用 Shiki。若改用 rehypeCodeFromHighlighter,則可搭配其他語法突顯器 (例如 Highlights) ,並使用 Shiki 以外的選項。請傳入一個函式,利用此外掛的 transformer 建立語法突顯器。
請停用預設外掛,再加入此外掛:
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',
};這是經過語法突顯的行內程式碼:`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 不支援的語言,會導致建置失敗。若要改用其他語言進行語法突顯,請設定 fallbackLanguage:
import { defineConfig } from 'fumadocs-mdx/config';
export default defineConfig({
mdxOptions: {
rehypeCodeOptions: {
fallbackLanguage: 'plaintext',
},
},
});更多選項
這些選項繼承自 Shiki,其他選項請參閱 Shiki 的文件。
How is this guide?
