Outlining SvelteKit blog setup with MDsveX, custom TOC, and Shiki highlighting
This detailed plan integrates a rehype plugin to extract H2/H3 headings into a table of contents embedded in MDsveX metadata, which is then consumed in SvelteKit routes. It also configures rehype-pretty-code with Shiki themes for dark/light mode switching via CSS variables, enabling SSR-friendly syntax highlighting that adapts to user preferences through CSS media queries or server-side detection. Key code snippets for svelte.config.js, the rehype TOC plugin, route loading, Svelte page usage, and CSS for theming are effectively combined to show a practical implementation approach.
Below is a minimal, “drop‑in” setup that hits all of the requirements:
- SvelteKit + MDsveX for Markdown/Svelte.
- A custom
rehype plugin that walks the AST, collects all h2/h3 headings into a TOC and injects it into the page’s exported metadata.
- Syntax highlighting with Shiki (via
rehype-pretty-code) using two themes (light/dark) so it matches the user’s color scheme, with no client‑side highlighting (all done server‑side).
1) svelte.config.js (or .ts)
import adapter from '@sveltejs/adapter-auto';
import { mdsvex } from 'mdsvex';
import rehypeSlug from 'rehype-slug';
import rehypePrettyCode from 'rehype-pretty-code';
import rehypeToc from './src/lib/rehype-toc.js'; // our custom plugin
import fs from 'node:fs';
const lightTheme = JSON.parse(fs.readFileSync('static/shiki-theme-light.json', 'utf8'));
const darkTheme = JSON.parse(fs.readFileSync('static/shiki-theme-dark.json', 'utf8'));
const mdsvexConfig = {
extensions: ['.md', '.svx'],
rehypePlugins: [
rehypeSlug, // adds id to headings based on text
rehypeToc, // collects h2/h3 -> metadata.toc
[
rehypePrettyCode,
{
theme: {
light: lightTheme,
dark: darkTheme
},
keepBackground: false // let your site/background control it
}
]
]
};
const config = {
extensions: ['.svelte', '.svx', '.md'],
preprocess: [mdsvex(mdsvexConfig)],
kit: {
adapter: adapter()
}
};
export default config;
You can use any Shiki JSON theme; put them in static/ or import directly from a package.
2) Custom TOC plugin: src/lib/rehype-toc.js
import { visit } from 'unist-util-visit';
import { toString } from 'hast-util-to-string';
import GithubSlugger from 'github-slugger';
/**
* Collects h2/h3 into metadata.toc, ensures headings have IDs.
*/
export default function rehypeToc() {
return (tree, file) => {
const slugger = new GithubSlugger();
const toc = [];
visit(tree, 'element', (node) => {
if (node.tagName === 'h2' || node.tagName === 'h3') {
const depth = node.tagName === 'h2' ? 2 : 3;
const title = toString(node).trim();
const slug = node.properties?.id || slugger.slug(title);
node.properties = node.properties || {};
node.properties.id = slug;
toc.push({ depth, title, slug });
}
});
const fm = (file.data.fm ||= {});
fm.toc = toc;
};
}
MDsveX merges file.data.fm into the compiled module’s metadata export, so you can access metadata.toc later.
3) Blog content (Markdown/SVX) lives in e.g. src/routes/blog/posts/hello-world.md
---
title: Hello World
date: 2024-04-01
---
## Intro
Content…
### Details
More…
```svelte
<script>
let count = 0;
</script>
<button on:click={() => count++}>Clicked {count} times</button>
### 4) Blog page route: `src/routes/blog/[slug]/+page.server.ts`
```ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
// adjust path if your posts folder is elsewhere
const post = await import(`../posts/${params.slug}.md`);
return {
Content: post.default, // the compiled Svelte component
meta: post.metadata // frontmatter + our injected toc
};
};
5) Blog page Svelte: src/routes/blog/[slug]/+page.svelte
<script lang="ts">
export let data;
const { Content, meta } = data;
</script>
<svelte:head>
<title>{meta.title}</title>
</svelte:head>
<article class="prose">
<Content />
</article>
<aside class="toc">
<h3>On this page</h3>
<ul>
{#each meta.toc as item}
<li class:item.depth === 3 ? 'toc-depth-3' : ''>
<a href={`#${item.slug}`}>{item.title}</a>
</li>
{/each}
</ul>
</aside>
<style>
.toc ul { list-style: none; padding: 0; margin: 0; }
.toc li { margin: 0.25rem 0; }
.toc-depth-3 { padding-left: 1rem; font-size: 0.95em; }
</style>
6) Shiki theme switching (SSR‑friendly)
rehype-pretty-code will bake all highlighting into the HTML. To match user dark/light preference, load both theme colors and switch with CSS. A simple approach:
- Give your
<html> a class of dark or light (from a cookie or Sec-CH-Prefers-Color-Scheme on the server).
- Or rely on
prefers-color-scheme media queries.
Example global CSS (src/routes/+layout.svelte or src/app.css):
:root {
color-scheme: light dark;
}
/* rehype-pretty-code sets data-theme on the <pre> wrapper */
pre[data-theme="light"], code[data-theme="light"] {
display: block;
}
pre[data-theme="dark"], code[data-theme="dark"] {
display: none;
}
@media (prefers-color-scheme: dark) {
pre[data-theme="light"], code[data-theme="light"] { display: none; }
pre[data-theme="dark"], code[data-theme="dark"] { display: block; }
}
/* Optional: style for line numbers, highlighted lines, etc. */
pre {
padding: 1rem;
border-radius: 0.5rem;
overflow-x: auto;
}
rehype-pretty-code emits two copies of each code block when you pass { theme: { light, dark } }, each annotated with data-theme="light" or data-theme="dark". The CSS above shows/hides the correct one based on prefers-color-scheme. If you prefer explicit toggles, add/remove a .dark class on <html> instead of the media query.
7) Optional: Server‑side theme detection
If you want to pick a theme class server‑side, read Sec-CH-Prefers-Color-Scheme or a user cookie in +layout.server.ts:
// src/routes/+layout.server.ts
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ request, cookies }) => {
const cookieTheme = cookies.get('theme'); // 'dark' | 'light' | undefined
const ch = request.headers.get('sec-ch-prefers-color-scheme'); // 'dark' | 'light' | null
const theme = cookieTheme ?? ch ?? 'light';
return { theme };
};
Then in +layout.svelte:
<script>
export let data;
const { theme } = data;
</script>
<svelte:head>
<html class={theme} />
</svelte:head>
And update your CSS to show/hide [data-theme="dark"] based on .dark on <html> instead of @media.
That’s it: Markdown/SVX posts are rendered by SvelteKit, the TOC is auto‑generated from h2/h3 and exposed via metadata.toc, and Shiki highlighting is pre‑rendered with light/dark themes switched via CSS or server‑detected preference.