Search code examples
sveltemathjax

How to use MathJax in a svelte project?


I am working on a svelte text editor project in svelte , the code is very simple (REPL) :

<script>
    let rawText
    let formatText = (text)=>{
        // Text Formating
        return text
    }
    $: formatedText = formatText(rawText)
</script>

<textarea bind:value={rawText}></textarea>
{#if formatedText}
    {formatedText}
{/if}

I need to be able to write math equations.

To do so I have found MathJax but I can't find a clean way to import it into my svelte app

I have tried multiples approach like

the npm way :

using :

npm i mathjax

and on the svelte component :

import MathJax from 'mathjax'

But when I do this the app turn white without any error

The svelte:head way :

The second solution I tried was to import MathJax from a cdn in a script tag like that :

<svelte:head>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script
        id="MathJax-script"
        async
        src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
</svelte:head>

And it kinda works because I can access MathJax functions in the browser console but I don't know to use them in my svelte app

capture

The hacky way :

The last solution I have found in this example leads to the same problem.

So my question is how to import mathjax in my svelte project or can I use something else?


Solution

  • I don't know if you finally used the example in your comment. I hope you did.

    For anyone else wanting a solution for this, I tried the following. (I don't know if it is correct for a Svelte application, but it worked, at least)

    The example found in the comment here says as follows:

    // Thanks to https://github.com/dpvc
    <script>
    MathJax = {
      tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
    };
    </script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
    

    So in my app/public/index.html file, I added the script pointing to the CDN, just as it says in the comment.

    After that, I tried using the Latex notation directly on the Svelte script, as:

    # Svelte file
    <script lang="ts">
      let equ = `$$x = \\frac{t}{3}$$`;
    </script>
    <main>
      {equ}
    </main>
    

    And it did work. 🎉

    At first, it wasn't working, so with my monke brain, I thought maybe it was because I didn't add the other script part to the index.html file. I added it and it worked. So maybe it was because the language server was not working or something else... I don't know for sure, I am using VSCode and after a restart and deleting that part, I worked. So that is my super investigation about it.