The <Code> component renders syntax highlighted code. It is useful when using a Markdown code block is not possible, for example, to render data coming from external sources like files, databases, or APIs.

example.md
## Welcome

Hello from **space**!

Import

import { Code } from '@astrojs/starlight/components';

Usage

Use the <Code> component to render syntax highlighted code, for example when displaying code fetched from external sources.

See the Expressive Code "Code Component" docs for full details on how to use the <Code> component and the list of available props.

import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('This could come from a file or CMS!');`;
export const fileName = 'example.js';
export const highlights = ['file', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
example.js
console.log('This could come from a file or CMS!');

Display imported code

In MDX files and Astro components, use Vite's ?raw import suffix to import any code file as a string. You can then pass this imported string to the <Code> component to include it on your page.

# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "jsxImportSource": "@builder.io/qwik",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "paths": {
      "@qwik-docs/framework": ["../packages/framework/src/index.ts"],
      "@qwik-docs/framework/*": ["../packages/framework/src/*"],
      "@qwik-docs/components": ["../packages/components/genfiles/qwik/src"]
    }
  },
  "include": ["src", "*.ts"]
}

<Code> Props

Implementation: Code.astro

The <Code> component accepts all the props documented in the Expressive Code "Code Component" docs.