Fumadocs

代码块(动态)

一个也能高亮显示代码的代码块

console.log("This is pre-rendered")

使用

🌐 Usage

客户端组件

🌐 Client Component

import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';

export function MyComp() {
  const code = `console.log("Hello World")`;

  return <DynamicCodeBlock lang="ts" code={code} />;
}

与 MDX CodeBlock 组件不同,这是一个可以在不使用 MDX 的情况下使用的客户端组件。它使用 Shiki 高亮显示代码,并使用默认组件来渲染代码。

🌐 Unlike the MDX CodeBlock component, this is a client component that can be used without MDX. It highlights the code with Shiki and use the default component to render it.

特点:

🌐 Features:

  • 使用 React.js 19 的 Suspense。
  • 可以在服务器上预渲染。
  • 在浏览器上延迟加载语言和主题。

选项

🌐 Options

import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';

<DynamicCodeBlock
  lang="ts"
  code='console.log("Hello World")'
  options={{
    themes: {
      light: 'github-light',
      dark: 'github-dark',
    },
    components: {
      // override components (e.g. `pre` and `code`)
    },
    // other Shiki options
  }}
/>;

服务器组件

🌐 Server Component

对于服务器组件的等效功能,你可以使用核心自带的工具:

🌐 For a server component equivalent, you can use the built-in utility from core:

import * as Base from 'fumadocs-ui/components/codeblock';
import { highlight } from 'fumadocs-core/highlight';
import { type HTMLAttributes } from 'react';

export async function CodeBlock({
  code,
  lang,
  ...rest
}: HTMLAttributes<HTMLElement> & {
  code: string;
  lang: string;
}) {
  const rendered = await highlight(code, {
    lang,
    components: {
      pre: (props) => <Base.Pre {...props} />,
    },
    // other Shiki options
  });

  return <Base.CodeBlock {...rest}>{rendered}</Base.CodeBlock>;
}

Last updated on

On this page