Search code examples
typescriptsveltemathjax

Using MathJax in a Svelte Project


I'm attempting to use MathJax in a svelte project. The problem I'm facing right now is that typescript will return an error when I try to use LaTeX functions, such as \matcal{Q} or \color{red}{Q}, the error being "Cannot find name 'Q'". Moreover, I can not define macros, neither in the MathJax configuration or in the HTML file itself.

So far I have:

  • Added MathJax via the CDN in app.html:
<head>
    <meta charset="utf-8" />
    <link rel="icon" href="%sveltekit.assets%/favicon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({"HTML-CSS": {
            preferredFont: "TeX", availableFonts: ["STIX","TeX"], linebreaks: { automatic:true }, EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) },
            loader: {load: ['[tex]/color']},
            tex2jax: { inlineMath: [ ["$", "$"], ["\\(", "\\)"] ], displayMath: [ ["$$","$$"], ["\\[", "\\]"] ], processEscapes: true, ignoreClass: "tex2jax_ignore|dno" },
            tex: {
                packages: {'[+]': ['color']},
                Macros: {
                    RR: "{\\bf R}"
                }
            },
            messageStyle: "none"
        });
    </script>
    <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
    %sveltekit.head%
</head>
  • Created a mathjax.ts file in /lib to add mathjax to a page after loading:
import { onMount } from 'svelte';

declare global {
    interface Window {
        MathJax: any;
    }
}

export function useMathJax() {
    onMount(() => {
        if (window.MathJax) {
            window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub]);
        }
    });
}
  • used that script in a +page.svelte file such as this:
<main>      
    <div class="header"> 
      $\mathcal{U}$
    </div>
</main>

Inline and block math works fine as long as it doesn't include any LaTeX functions. Has anyone figured out a way to this or see an obvious flaw in my configuration?


Solution

  • {/} are used for interpolating JS values in the template, you can e.g. put them in a string and interpolate that:

    <div class="header"> 
      {'$\\mathcal{U}$'}
    </div>