Use Highlighted Code

Reactive Shiki token lines for code blocks, including incremental updates.

Loading preview…

Installation

Usage

Call during component initialization and pass getters for reactive source and language values. current returns plain text while the highlighter loads, then styled token arrays accepted by CodeBlock.Line. Unsupported languages remain plain text. Install Code Block separately for the example below.

1<script lang="ts">
2  import { useHighlightedCode } from "~/hooks/use-highlighted-code.svelte.js";
3  import * as CodeBlock from "~/components/code-block";
4  let code = $state('const greeting = "hello";');
5  const lines = useHighlightedCode(() => code, () => "typescript");
6</script>
7
8<CodeBlock.Root>
9  <CodeBlock.Content lineNumbers>
10    {#each lines.current as line, index (index)}
11      <CodeBlock.Line code={line} />
12    {/each}
13  </CodeBlock.Content>
14</CodeBlock.Root>

Includes lazy language loading, GitHub light and dark token colors, ANSI, and common language aliases such as ts, js, and sh. Extend highlighter.ts to enable additional languages.