web/src/lib/content/posts/using-svelte-in-markdown.md
Ref: Mdsvex
Here are some examples illustrating how to use Mdsvex in a Svelte application:
Example 1: Basic Markdown with Svelte Component Create a file named example.svx:
---
title: "Interactive Markdown Example"
---
<script>
import Counter from '../components/Counter.svelte';
</script>
# {title}
This is an example of combining Markdown with a Svelte component:
<Counter />
In this example:
Example 2: Custom Layouts with Mdsvex Assuming you have a layout component at src/lib/layouts/BlogLayout.svelte:
<!-- BlogLayout.svelte -->
<script>
export let title;
</script>
<div class="blog-post">
<h1>{title}</h1>
<slot />
</div>
Now, to use this layout in your Markdown:
---
title: "My Favorite Layout"
layout: "../lib/layouts/BlogLayout.svelte"
---
## Markdown with Custom Layout
This Markdown file will be wrapped by the `BlogLayout`.
Example 3: Using Frontmatter Variables in Markdown
---
author: "John Doe"
date: "2024-11-15"
---
# Blog Post
By {author} on {date}
Here's some markdown content. You can reference frontmatter values directly in the body.
Example 4: Interactive Elements in Markdown
---
title: "Interactive Chart"
---
<script>
import { Chart } from '../components/Chart.svelte';
</script>
# {title}
Below is an interactive chart:
<Chart />
To make these work, you need to configure your SvelteKit project:
npm install -D mdsvex
In your svelte.config.js:
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { mdsvex } from 'mdsvex';
/** @type {import('mdsvex').MdsvexOptions} */
const mdsvexOptions = {
extensions: ['.svx'],
};
/** @type {import('@sveltejs/kit').Config} */
const config = {
extensions: ['.svelte', '.svx'],
preprocess: [
vitePreprocess(),
mdsvex(mdsvexOptions),
],
kit: {
adapter: adapter()
}
};
export default config;
Place your .svx files in the src/routes directory or subdirectories, and SvelteKit will automatically handle them as routes.
These examples show how you can integrate Mdsvex into your Svelte application, combining the simplicity of Markdown with the interactivity of Svelte components. Remember, any Svelte component you want to use within Markdown must be exported from a .svelte file and imported in your .svx file.