Building a Markdown Blog with SvelteKit
Building a Markdown Blog with SvelteKit
Creating a markdown blog is an excellent way to learn SvelteKit's core concepts. Let's build one!
Why Markdown?
Markdown is perfect for blogs because:
- Simple syntax - Easy to write and read
- Portable - Plain text files that work everywhere
- Version control friendly - Git diffs work great
- Fast - No database needed for simple blogs
Project Structure
Here's how we'll organize our blog:
src/
āāā posts/
ā āāā post-one.md
ā āāā post-two.md
ā āāā post-three.md
āāā routes/
āāā blog/
āāā +page.svelte # List all posts
āāā +page.ts # Load all posts
āāā [slug]/
āāā +page.svelte # Display single post
āāā +page.ts # Load single post
Required Dependencies
We need two packages:
npm install marked gray-matter
marked- Converts markdown to HTMLgray-matter- Parses YAML frontmatter
Frontmatter
Each markdown file starts with YAML metadata:
---
title: My Blog Post
date: 2024-03-05
author: Mark
description: A great blog post
---
This metadata is perfect for:
- Displaying post previews
- Sorting posts by date
- Adding SEO meta tags
Loading Posts
In SvelteKit, we use load functions to fetch data:
// +page.ts
export async function load() {
const posts = await getAllPosts();
return { posts };
}
The returned data is available in your component via data prop!
Rendering Markdown
Use marked to convert markdown to HTML:
import { marked } from 'marked';
const html = marked(markdown);
Then render it in Svelte:
{@html html}
Conclusion
Building a markdown blog teaches you:
- File-based routing
- Load functions
- Dynamic routes
- Static site generation
It's the perfect first SvelteKit project! š