Comprehending the Objective
I'm focused on grasping the user's need: a SvelteKit blog guide. It's becoming clearer that MDsveX is critical, and there's a strong emphasis on dynamic routes. I'm prioritizing understanding how to best organize and present the information to the user.
Developing the Blueprint
My focus is solidifying the guide's structure. I'm moving beyond just the requirements and I'm developing a step-by-step implementation plan: setting up the project, installing dependencies, configuring MDsveX, and handling images. I'm now also thinking about the sample content creation phase, considering the use of frontmatter and image inclusion.
Detailing the Implementation
Now I'm delving deeper into the code. I've decided to prioritize @sveltejs/enhanced-img for image handling, focusing on how to integrate it correctly within the Vite configuration and MDsveX setup. I'm also refining the approach to the dynamic route, mapping the import of Markdown files. Moreover, I'm leaning toward an import.meta.glob implementation for optimal performance, rather than using the API approach for fetching posts on the index page.
Finalizing the Strategy
I've refined my image strategy. Now, I'm leaning toward using @sveltejs/enhanced-img with a custom <Image /> component within MDsveX, to get full optimization. I'm also considering the use of import.meta.glob for improved post fetching performance and how to best organize the content for a clear, concise guide.
Optimizing the Implementation
I'm now prioritizing the implementation phase. Specifically, I'm focusing on the MDsveX setup and image optimization strategy, which will involve @sveltejs/enhanced-img. I'm starting to build a custom <Image /> component within MDX, to enhance the performance of the images, and the approach for handling dynamic routes.
Formulating the Outline
I'm now consolidating the steps into a logical flow. I'm focusing on the MDsveX setup and @sveltejs/enhanced-img integration for image optimization. Specifically, I'm thinking about the component and route structure.
Developing the Implementation
Now, I'm fully immersed in the coding phase, constructing a custom <Image /> component, for integration with @sveltejs/enhanced-img. I'm using import.meta.glob to efficiently fetch the Markdown files and refine the dynamic route for each blog post. I'm focusing on simplicity and clarity, making the guide easy for the user to follow.
Here is a complete, step-by-step guide to building a SvelteKit blog using MDsveX (for Markdown/MDX), Dynamic Routes (slug-based navigation), and @sveltejs/enhanced-img (for modern image optimization).
Prerequisites
- Node.js installed
- Basic understanding of SvelteKit
Step 1: Initialize SvelteKit Project
Create a skeleton project with TypeScript.
npm create svelte@latest my-blog
# options: Skeleton project, TypeScript, No to others for simplicity
cd my-blog
npm install
Step 2: Install Dependencies
We need MDsveX and the official Svelte image optimization plugin.
# Install MDsveX and its peer dependencies
npm install -D mdsvex shiki
# Install Image Optimization
npm install -D @sveltejs/enhanced-img
Step 3: Configure Vite and Svelte
We need to tell Vite to handle images and tell Svelte to treat .md files as components.
1. Update vite.config.ts:
Add the enhanced image plugin.
import { sveltekit } from '@sveltejs/kit/vite';
import { enhancedImages } from '@sveltejs/enhanced-img';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
enhancedImages(), // Must be before sveltekit()
sveltekit()
]
});
2. Update svelte.config.js:
Configure MDsveX to process markdown files.
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { mdsvex } from 'mdsvex';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// 1. Add .md to extensions
extensions: ['.svelte', '.md'],
// 2. Add mdsvex to preprocessors
preprocess: [
vitePreprocess(),
mdsvex({
extensions: ['.md'],
// Optional: Add a layout specifically for markdown files
// layout: { _: './src/lib/layouts/post.svelte' }
})
],
kit: {
adapter: adapter()
}
};
export default config;
Step 4: Create Blog Content & Assets
Let's organise our posts and images.
- Create folder
src/posts.
- Create folder
src/lib/assets.
- Place a sample image (e.g.,
mountain.jpg) into src/lib/assets.
Create a markdown file: src/posts/first-post.md.
---
title: "No Silver Bullets"
date: "2023-10-25"
description: "Why technology choices are always trade-offs."
published: true
---
<script>
// Import the image to trigger optimization
import mountain from '$lib/assets/mountain.jpg?w=800&format=webp';
</script>
# Hello World
This is my first post written in **MDsveX**.
Here is an optimized image served by Vite:
<!-- The 'enhanced-img' plugin allows us to just use standard img tags -->
<img src={mountain} alt="A beautiful mountain" />
You can also use standard Markdown syntax, but importing gives you optimization powers!
Step 5: Creates Utilities to Fetch Posts
We need a way to read the filesystem and get a list of all blog posts for our index page.
Create src/lib/utils.ts:
export type Post = {
title: string;
slug: string;
date: string;
description: string;
published: boolean;
};
export async function getPosts() {
let posts: Post[] = [];
// Import all .md files from src/posts/
const paths = import.meta.glob('/src/posts/*.md', { eager: true });
for (const path in paths) {
const file = paths[path];
// Retrieve the filename to use as the slug
const slug = path.split('/').at(-1)?.replace('.md', '');
if (file && typeof file === 'object' && 'metadata' in file && slug) {
const metadata = file.metadata as Omit<Post, 'slug'>;
const post = { ...metadata, slug } satisfies Post;
if (post.published) {
posts.push(post);
}
}
}
// Sort by date
posts = posts.sort((first, second) =>
new Date(second.date).getTime() - new Date(first.date).getTime()
);
return posts;
}
Step 6: Create the Blog Listing Page
Create the route /blog.
src/routes/blog/+page.server.ts:
import { getPosts } from '$lib/utils';
export async function load() {
const posts = await getPosts();
return { posts };
}
src/routes/blog/+page.svelte:
<script lang="ts">
export let data;
</script>
<div class="container">
<h1>My Blog</h1>
<div class="grid">
{#each data.posts as post}
<article class="card">
<a href="/blog/{post.slug}">
<h2>{post.title}</h2>
</a>
<p class="date">{post.date}</p>
<p>{post.description}</p>
</article>
{/each}
</div>
</div>
<style>
/* Simple CSS for demonstration */
.container { max-width: 800px; margin: 0 auto; padding: 2rem; }
.card { margin-bottom: 2rem; padding: 1rem; border: 1px solid #eee; border-radius: 8px; }
.date { color: #666; font-size: 0.9rem; }
h2 { margin: 0 0 0.5rem 0; }
a { text-decoration: none; color: inherit; }
a:hover { text-decoration: underline; }
</style>
Step 7: Create the Dynamic Post Route
Now we handle the individual blog post view: /blog/[slug].
src/routes/blog/[slug]/+page.ts:
Note: We use +page.ts (universal load) instead of .server.ts because MDsveX compiles to Svelte components which need to be mounted.
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: PageLoad = async ({ params }) => {
try {
// Dynamic import of the markdown file based on slug
const post = await import(`../../../posts/${params.slug}.md`);
return {
content: post.default, // The compiled Svelte component
meta: post.metadata // Such as title, date, etc.
};
} catch (e) {
throw error(404, `Could not find ${params.slug}`);
}
};
src/routes/blog/[slug]/+page.svelte:
<script lang="ts">
export let data;
// Rename for clarity in template
$: ({ content: PostContent, meta } = data);
</script>
<svelte:head>
<title>{meta.title}</title>
<meta name="description" content={meta.description} />
</svelte:head>
<article class="prose">
<header>
<h1>{meta.title}</h1>
<p class="date">Published on {meta.date}</p>
</header>
<!-- Render the MDsveX component -->
<div class="content">
<svelte:component this={PostContent} />
</div>
</article>
<style>
.prose { max-width: 700px; margin: 0 auto; padding: 2rem; line-height: 1.6; }
header { margin-bottom: 2rem; border-bottom: 1px solid #eee; padding-bottom: 1rem; }
.date { color: #666; }
/* You can add global styles for markdown content here or in app.css */
:global(.content img) { max-width: 100%; height: auto; border-radius: 8px; }
</style>
Summary of Features Implemented
- MDsveX: We configured
svelte.config.js to treat .md files as Svelte components. This allows you to write Markdown and even import Svelte components inside your markdown files.
- Image Optimization: By using
@sveltejs/enhanced-img and importing the image inside the .md file script tag (import img from...), Vite will automatically convert images to WebP/Avif, resize them, and cache them at build time.
- Dynamic Routing:
- We used
[slug] to capture the URL parameter.
- We used
import.meta.glob to fetch all posts for the list page.
- We used dynamic
import() in the load function to fetch the specific markdown file requested.
How to Run
npm run dev
Visit http://localhost:5173/blog to see your list, and click the post to see the rendered Markdown with the optimized image.