Syntax Highlighting

Thilo Maier •
  • Syntax Highlighting
  • Markdown

CodeSnippet component

You can use the CodeSnippet component from this package without any additional dependencies or setup.

Code fences with mdsvex

Setup

You need to set up code fences in your mdsvex options. You first need to create and await the highlighter in svelte.config.js:

const highlighter = await createHighlighter({
	themes: ['min-light', 'min-dark'],
	langs: [
		'bash',
		'html',
		'javascript',
		'json',
		'markdown',
		'svelte',
		'text',
		'typescript',
		'yaml',
		'xml'
	]
});

Then you add the highlight option to your mdsvex options:

highlight: {
	highlighter: async (code, lang = 'text') => {
		const html = escapeSvelte(
			highlighter.codeToHtml(code, {
				lang,
				themes: {
					light: 'min-light',
					dark: 'min-dark'
				}
			})
		);
		return `{@html `${html}` }`;
	};
}

escapeSvelte is a helper from package mdsvex to escape Svelte syntax in the generated HTML.

Examples

Bash

echo "Hello, world!"

HTML

<h1>Hello, world!</h1>

JavaScript

console.log('Hello, world!');

JSON

{
	"name": "John",
	"age": 30
}

Markdown

# Hello, world!

Svelte

<script>
	let message = $state('Hello, world!');
</script>

<h1>{message}</h1>

Text

Hello, world!

TypeScript

export type User = {
	name: string;
	age: number;
};

YAML

name: John
age: 30

XML

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>