How to import markdown files in svelte kit?

Viewed 948
<script>
    import Markdown from '../components/Markdown.svelte';
    import path from '../../static/assets/docs/overview.md';
</script>

<article class="prose prose-red max-w-none">
    <Markdown markdown={path} />
</article>

Here's the warning:

files in the public directory are served at the root path.
Instead of /static/assets/docs/overview.md?import, use /assets/docs/overview.md?import.

If I use import path from '/assets/docs/overview.md'; I get the following error:

9:30:18 PM [vite] Internal server error: Cannot import non-asset file /assets/docs/overview.md which is inside /public.JS/CSS files inside /public are copied as-is on build and can only be referenced via <script src> or <link href> in html.
  Plugin: vite:import-analysis
  File: /Users/me/www/underwriting-ui/src/routes/docs.svelte
      at TransformContext.transform (/Users/me/www/underwriting-ui/node_modules/vite/dist/node/chunks/dep-713b45e1.js:67350:31)
      at async Object.transform (/Users/me/www/underwriting-ui/node_modules/vite/dist/node/chunks/dep-713b45e1.js:42397:30)
      at async doTransform (/Users/me/www/underwriting-ui/node_modules/vite/dist/node/chunks/dep-713b45e1.js:56738:29)
1 Answers

I have the same scenario - documentation in static markdown from which I need to generate HTML at build time. I ended up using vite-plugin-markdown.

add this to your vite.config.js

import { plugin as markdown } from 'vite-plugin-markdown'

const config = {
  plugins: [markdown({ mode: ['html', 'toc'], ...})], ...
}

then in your svelte component

import { toc, html } from '~/docs/api/auth.md'

I'm especially happy about "toc", which outputs something like.

[{ level: '1', content: 'foo' }, { level: '2', content: 'bar' }, ...]
Related