javascriptsveltesvelte-3prismjs

Svelte js with store and Prism library issue


I'm trying to add the Prism library (https://prismjs.com/) to the Svelte 3 app. Once I add the Prism script, store variables stop been updated.

store.js

import { writable } from 'svelte/store';
const store = writable({
    num: 1
});
export default store;

App.svelte

<script>
    import store from './store';
    import { onMount } from 'svelte';
    let prismScript = null;

    onMount(async () => {
        let prismScript = document.createElement('script');
        prismScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/prism.min.js';
        document.head.append(prismScript);
    });
</script>

<button type="button" on:click={ evt => { store.update($store.num++) } }>Button</button>

<!-- this one works -->
<p>{$store.num}</p>

<!-- this one doesn't work -->
<pre class="language-html">
 <code>{$store.num}</code>
</pre>

Please see also Svelte REPL example here: https://svelte.dev/repl/99b7294424a84bcd9e6212cfbd537a77?version=3

Thanks


Solution

  • <script>
        import store from './store';
    
        let prismLoaded = false;
        let html = '';
        $: {
            if (prismLoaded && window.Prism) {
                html = `<div>${$store.num}</div>`;
                html = Prism.highlight(html, Prism.languages.html, 'html');
            }
        }
    </script>
    
    <svelte:head>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/themes/prism.min.css" rel="stylesheet" />
        <script
            src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/prism.min.js" 
            async data-manual on:load={() => prismLoaded = true}
        ></script>
    </svelte:head>
    
    <button type="button" on:click={() => $store.num++}>Button</button>
    <pre><code>{@html html}</code></pre>
    

    https://svelte.dev/repl/a75062e0ed1c48a4bca5c83a744f7112