Parse markdown inside a svelte component

Viewed 2919

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.

4 Answers

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>

I use marked. I game the system by assigning a variable that svelte can see to marked.

<script>
  let _marked = marked

  let md = `
    # Hello

    ## How are you?

    This text is _bold_
  `
</script>

<div>
{@html _marked(md)}
</div>

The problem with the accepted answer is that it relies on @html which is not secure.

There is a svelte component that renders markdown without using @html

https://www.npmjs.com/package/svelte-markdown

yarn add svelte-markdown
<script>
  import SvelteMarkdown from 'svelte-markdown'
  const source = `
  # This is a header

This is a paragraph.

* This is a list
* With two items
  1. And a sublist
  2. That is ordered
    * With another
    * Sublist inside

| And this is | A table |
|-------------|---------|
| With two    | columns |`
</script>

<SvelteMarkdown {source} />
Related