close
  • English
  • CodeBlockRuntime non-ejectable

    Warning

    This component currently does not support copying source code via the eject command. Custom Theme

    CodeBlockRuntime renders runnable code blocks at runtime.

    Usage

    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!')

    Pass lang, title, and code to render the block; shikiOptions customizes highlighting and also supports transformers.

    Warning

    It is recommended to use CodeBlockRuntime only when necessary, as it increases runtime bundle size, especially when multiple languages need to be included, and cannot benefit from compile-time highlighting performance.

    Using shiki options

    Here is an example using a transformer for line highlighting:

    foo.mdx
    import { CodeBlockRuntime } from '@rspress/core/theme';
    import { transformerNotationHighlight } from '@shikijs/transformers';
    
    <CodeBlockRuntime
      lang="ts"
      title="highlight.ts"
      code={`console.log('Highlighted'); // [!code highlight]
    // [!code highlight:1]
    console.log('Highlighted');
    console.log('Not highlighted');`}
      shikiOptions={{
        transformers: [transformerNotationHighlight()],
      }}
    />
    highlight.ts
    console.log('Highlighted'); // [!code highlight]
    // [!code highlight:1]
    console.log('Highlighted');
    console.log('Not highlighted');

    Importing file content

    You can use the ?raw query to import file content as a string and pass it to the code prop. See Rsbuild - Static Assets for details.

    foo.mdx
    import { CodeBlockRuntime } from '@rspress/core/theme';
    import codeContent from './example.ts?raw';
    
    <CodeBlockRuntime lang="ts" title="example.ts" code={codeContent} />

    This approach is suitable for scenarios where you need to dynamically display external file content, such as showing example code files.

    Warning

    If you just need to reference external files as code blocks, it is recommended to use the static file code block syntax, which is processed at compile time with better performance and smaller bundle size.