Blogging on SvelteKit

Published Wed Jan 17 2024

Svelte is by far my favorite UI framework for the web. Where React is “just JavaScript,” I find Svelte extremely comfortable to learn and use because Svelte components are structured like HTML documents. You place your scripts in a <script> tag and your styles in a <style> tag. Everything else is just markup!

These ease of getting things done is taken up a notch once you add in SvelteKit. When it came time to set up my personal site SvelteKit was a no brainer.

Adders

Bootstrapping a Svelte project is quick, if you take a look at the docs all you need to do is run npm create svelte@latest my-app. This is not where you should stop though. Svelte Add provides quick scripts to boilerplate common project dependencies. For my blog I needed 2: TailwindCSS and mdsvex.

$ npx svelte-add@latest tailwindcss
$ npx svelte-add@latest mdsvex

Running these adders not only installs the dependencies, they will create new configuration files and extend your existing Svelte configuration file!

Dynamically Rendering Markdown

Once I had assembled my power tools I was ready to sprinkle some code on top. Here is all the code required to render this blog post!

First we create a +page.ts file which SvelteKit will use to preload data for our route. Our slug parameter is provided by SvelteKit’s router which we can then use to load markdown. Our adder has already configured mdsvex to load any .md file as Svelte components, returned to us named default.

// +page.ts
export async function load({ params }) {
	const postData = await import(`../${params.slug}.md`);
	return {
		Content: postData.default,
		metaData: { ...postData.metaData, slug: params.slug }
	};
}

Once we’ve imported our markdown file all we need to do is consume that data in our Svelte component. Note that Content is a name I’ve chosen in the above page handler.

svelte:component is a special Svelte element for dynamically mounting a component. Coming from React I appreciate this over rendering a dynamic component with JSX tags.

<!-- +page.svelte --->
<script lang="ts">
	export let data;
	let { Content } = data;
</script>

<svelte:component this={Content} />

With this tiny bit of code you can have a blog up and running in no time. For bonus points I recommend (and am using) the tailwind typography plugin to make your markdown pretty. Thank you Svelte and mdsvex developers!