For AI agents: the complete documentation index is available at https://rspress.rs/zh/llms.txt, the full documentation bundle is available at https://rspress.rs/zh/llms-full.txt, and this page is available as Markdown at https://rspress.rs/zh/ui/components/code-block-runtime.md.
close

CodeBlockRuntime non-ejectable

Warning

该组件目前暂不支持 自定义主题 通过 eject 命令复制源码。

CodeBlockRuntime 用于在运行时渲染可执行的 代码块。

用法

index.mdx
import { CodeBlockRuntime } from '@rspress/core/theme';

export default function Page() {
  return (
    <CodeBlockRuntime
      lang="js"
      title="index.js"
      code={`console.log('Hello World!')`}
      shikiOptions={{}}
    />
  );
}
index.js
console.log('Hello World!')

传入 lang、title、code 渲染代码块;shikiOptions 可自定义高亮配置,也支持 transformers。

Warning

建议仅在必要条件下使用 CodeBlockRuntime,因为它会增加运行时的包体积,尤其是在需要引入多门语言的时候,并且无法享受编译时高亮带来的性能优势。

使用 Shiki 选项

行高亮、单词高亮、diff、focus 和 error/warning 注释语法默认启用。使用 shikiOptions.transformers 添加自定义 transformer,或通过相同的 name 覆盖内置项。

以下是一个无需配置的行高亮示例:

foo.mdx
import { CodeBlockRuntime } from '@rspress/core/theme';

<CodeBlockRuntime
  lang="ts"
  title="highlight.ts"
  code={`console.log('Highlighted'); // [!code highlight]
// [!code highlight:1]
console.log('Highlighted');
console.log('Not highlighted');`}
/>
highlight.ts
console.log('Highlighted'); // [!code highlight]
// [!code highlight:1]
console.log('Highlighted');
console.log('Not highlighted');

导入文件内容

可以使用 ?raw query 将文件内容作为字符串导入,然后传递给 code prop。详见 Rsbuild - 静态资源。

foo.mdx
import { CodeBlockRuntime } from '@rspress/core/theme';
import codeContent from './example.ts?raw';

<CodeBlockRuntime lang="ts" title="example.ts" code={codeContent} />

这种方式适用于需要动态展示外部文件内容的场景,比如展示示例代码文件。

Warning

如果只是需要引用外部文件作为代码块展示,更推荐使用静态的文件代码块语法,它在编译时处理,性能更好且包体积更小。