Implement a SvelteKit blog with MDsveX and create a custom rehype plugin that automatically generates a table of contents from H2/H3 tags and injects it into the page data. Also add syntax highlighting with shiki using a custom theme that matches the user's dark/light mode preference, server-side rendered.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
export function formatDate(date: Date): string {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(date);
}
export function calculateReadingTime(text: string): string {
const wordsPerMinute = 200;
const words = text.trim().split(/\s+/).length;
const minutes = Math.ceil(words / wordsPerMinute);
return `${minutes} min read`;
}
9. Example Blog Post
src/posts/getting-started.md
markdown
---
title: Getting Started with SvelteKit
description: A comprehensive guide to building modern web applications with SvelteKit
date: 2024-01-15
author: John Doe
tags: [sveltekit, svelte, tutorial]
published: true
---
# Getting Started with SvelteKit
Welcome to this comprehensive guide! We'll explore the basics of SvelteKit.
## What is SvelteKit?
SvelteKit is a framework for rapidly developing robust, performant web applications using Svelte.
### Key Features
- **Fast**: Optimized performance out of the box
- **Flexible**: Works with any deployment platform
- **Full-stack**: Built-in routing, server-side rendering, and more
## Installation
Here's how to get started:
```bash
npm create svelte@latest my-app
cd my-app
npm install
npm run dev
Project Structure
Your new project includes:
typescript
src/
├── lib/ # Reusable components and utilities
├── routes/ # Application routes
└── app.html # Root HTML template
Creating Pages
Pages are automatically created from files in src/routes:
svelte
<script>
export let data;
</script>
<h1>{data.title}</h1>
✅ Auto-generated Table of Contents - Rehype plugin scans h2/h3 tags and builds TOC tree
✅ Dual-theme Syntax Highlighting - Shiki generates both light and dark versions
✅ Server-Side Rendering - All processing happens at build time
✅ Dark/Light Mode Support - CSS prefers-color-scheme media query integration
✅ Smooth Heading Scrolling - Active section highlighting with scroll tracking
✅ Tag Filtering - Filter posts by tags on blog list
✅ Reading Time - Calculate reading time from content
✅ Responsive Design - Sidebar collapses on mobile
This implementation provides a production-ready SvelteKit blog with advanced markdown processing, automatic TOC generation, and beautiful syntax highlighting with theme support!
import type { Plugin } from 'unified';
import type { Root, Element, Text } from 'hast';
import { visit, SKIP } from 'unist-util-visit';
import { getHighlighter, type Highlighter } from 'shiki';
interface ShikiOptions {
themes?: {
light?: string;
dark?: string;
};
}
let highlighterInstance: Highlighter;
async function getShikiHighlighter(): Promise<Highlighter> {
if (!highlighterInstance) {
highlighterInstance = await getHighlighter({
themes: ['github-light', 'github-dark'],
langs: [
'javascript',
'typescript',
'svelte',
'html',
'css',
'bash',
'sh',
'json',
'yaml',
'sql',
'python',
'rust',
'go',
'java',
'csharp',
],
});
}
return highlighterInstance;
}
interface CodeElement extends Element {
properties: {
className?: string[];
};
children: Array<Text | Element>;
}
const plugin: Plugin<[ShikiOptions?], Root> = () => {
return async (tree: Root) => {
const highlighter = await getShikiHighlighter();
const tasks: Promise<void>[] = [];
visit(tree, 'element', (node: Element, index, parent) => {
if (node.tagName === 'pre' && node.children[0]?.type === 'element') {
const codeEl = node.children[0] as CodeElement;
if (codeEl.tagName === 'code') {
const className = codeEl.properties?.className?.[0] ?? '';
const lang = className.replace('language-', '');
const code = extractText(codeEl);
// Skip if no language specified or code is empty
if (!lang || !code.trim()) return;
tasks.push(
(async () => {
try {
// Generate both light and dark themed code
const lightHtml = highlighter.codeToHtml(code, {
lang,
theme: 'github-light',
});
const darkHtml = highlighter.codeToHtml(code, {
lang,
theme: 'github-dark',
});
// Create wrapper with theme support
const wrapper: Element = {
type: 'element',
tagName: 'div',
properties: {
className: ['code-block', `language-${lang}`],
dataLanguage: lang,
},
children: [
{
type: 'element',
tagName: 'div',
properties: { className: ['code-light'] },
children: [
{
type: 'raw',
value: lightHtml,
} as any,
],
},
{
type: 'element',
tagName: 'div',
properties: { className: ['code-dark'] },
children: [
{
type: 'raw',
value: darkHtml,
} as any,
],
},
],
};
// Replace pre with wrapper
if (parent?.type === 'element' && index !== undefined) {
parent.children[index] = wrapper;
}
} catch (err) {
console.error(`Error highlighting code for language ${lang}:`, err);
}
})()
);
return SKIP;
}
}
});
await Promise.all(tasks);
};
};
function extractText(node: CodeElement): string {
let text = '';
for (const child of node.children) {
if (child.type === 'text') {
text += child.value;
} else if (child.type === 'element') {
text += extractText(child as CodeElement);
}
}
return text;
}
export default plugin;