Search code examples
node.jsmarkdownsvelte

Parse markdown inside a svelte component


Please excuse me if this is a naive question. I would like to parse markdown inside a Svelte component, something like

<script>
  --- import some markdownLibrary ---
  export let text; // text is a markdown param
</script>

markdownLibrary.render({text})

I can't use markdown-it or marked as require isn't available.

I feel like I'm missing the bigger picture here. What is the 'svelte' way of doing this? Any pointer would help.


Solution

  • Using markdown is simple in Svelte, but you have to remember that a lot of markdown libraries expect to find node/requirejs etc, so you have to configure your bundler correctly to accomodate this.

    To simply use markdown in Svelte, pick a library which supports modern JavaScript out of the box:

    <script>
      import snarkdown from 'snarkdown'
    
      let md = `
        # Hello
    
        ## How are you?
    
        This text is _bold_
      `
    </script>
    
    <div>
    {@html snarkdown(md)}
    </div>