parse() is undefined using marked in Svelte app

442 Views Asked by At

I am trying to render some markdown in my Svelte app but am having trouble rendering with marked. I have install locally via npm and marked is present in my package.config. Also when I access marked I can see the parse() function with intellisense.

When I run the app and access the location though, I get the below error.

ServiceDetail.svelte:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'parse')
    at create_each_block_1 (ServiceDetail.svelte:27:57)
    at create_fragment (ServiceDetail.svelte:26:23)
    at init (index.mjs:2017:37)
    at new ServiceDetail (ServiceDetail.svelte:4:14)
    at createProxiedComponent (svelte-hooks.js?v=92e3ea1b:341:9)
    at new ProxyComponent (proxy.js?v=92e3ea1b:242:7)
    at new Proxy<ServiceDetail> (proxy.js?v=92e3ea1b:349:11)
    at create_if_block_2 (+page.svelte:4:29)
    at create_fragment (+page.svelte:11:32)
    at init (index.mjs:2017:37)

This is my code. Any idea what I'm missing here?

<script lang="ts">
  import ContactButton from "../../ContactButton.svelte";
  import { marked } from "marked";
  export let service;
</script>
...
...
          <div class="col-lg-15">
              <div class="card-span-img">
                <span>
                  <i class="{service.faIcon} fs-4 text-success"></i>
                </span>
              </div>
              <div class="card-body pt-6 pb-4 text-dark service-detail bg-200">
                <h5 class="mb-2"></h5>
                {#each service.detail.paragraphs as paragraph}
                  <p class="card-text markdown">{marked.parse("# TEST")}</p>
                {/each}
                <p><u>References</u></p>
                <ul>
                  {#each service.detail.links as link}
                    <li><a href="{link.url}" class="card-link" target="_blank" rel="noreferrer">{link.text} </a></li>
                  {/each}
                </ul>
                <ContactButton />
              </div>
          </div>
1

There are 1 best solutions below

1
On BEST ANSWER

The functions are directly exported, both marked and parse should work:

<script>
    import { parse, marked } from 'marked';
</script>

{parse('# hi')}
{marked('# hi')}

REPL

If that is not the case, the wrong file might be imported (there are multiple formats).
You can manually point to the ESM version like this:

import { parse, marked } from 'marked/lib/marked.esm.js';

marked currently does not publish its own types, so you probably have @types/marked installed. Note that those third-party type definitions may not necessarily be up to date/accurate.