Dynamically importing markdown file into Svelte throwing 404 error

Viewed 496

I am building an app in Svelte where I want markdown files to be imported and rendered in a component. I found a really good blog article outlining how to do this which I have followed. However I have come across a really weird issue. I can dynamically import the markdown file if the path to that file is 'hard coded', like so:

<script>
    import Markdown from './Markdown.svelte';
    import { onMount } from 'svelte';
    let exampleMarkdown = '';

    onMount(async () => {
        exampleMarkdown = (await import('./md/example.md')).default;
    });
</script>

<Markdown markdown={exampleMarkdown} />

But I need to be able to dynamically load a md file based on what link the user clicks, therefore I need the import file path to be created dynamically. But when I try this it isn't working:

<script>
    import Markdown from './Markdown.svelte';
    import { onMount } from 'svelte';
    let exampleMarkdown = '';

    onMount(async () => {
        // in the real thing this file path would be a string created depending on what link was clicked
        const filePath = './md/example.md';
        exampleMarkdown = (await import(filePath)).default;
    });
</script>

<Markdown markdown={exampleMarkdown} />

The second one doesn't work and i get a 404 error in the browser console:

App.svelte:22 GET http://localhost:5000/build/md/example.md net::ERR_ABORTED 404 (Not Found)

My md files are stored in a src/md folder, so why would a dynamically created file path string cause it to look in the build folder instead? I'm probably being really dense here, but I can't see one would work and the other wouldn't.

Thanks.

1 Answers

When using the hard coded version it knows during compilation which file it has to load so it will bundle it with your app.

With the dynamic version it doesn't and will try to load the markdown file during runtime instead. The problem now is that the runtime version (the one you ship to your users) is run in the build folder and does not have access to the src folder.

Just think of how this would run once you upload it to a server to host the website: normally you only copy the content of the build folder, so where would it ever get these files from ?

Fixing this is actually straightforward: copy the md files to your build folder and upload them with the rest of your app.

Related