POSTS / Support Variables in Markdown Latex with `rehype-katex-svelte`

Published: 2024-01-25

As this issue shows, MDsveX still has some issues in showing Markdown Latex.

The issue I met is using variables in Latex like this:

rac{1}{n}

As author says, the biggest issue is that svelte tries to evaluate anything in curly brackets. So expressions like kn1k_{n-1} will throw an error that n is not defined and expressions like k21k_{2-1} will come out as k1k_{1} because svelte will actually evaluate them.

Then one guy shared his solution in this comment. He made a package called rehype-katex-svelte as MDsveX plugin to solve the whole problem and it works well for me.

Steps:

run the following command to add them in project:

yarn add -D [email protected]
yarn add -D rehype-katex-svelte

config them in svelte.config.js:

import remarkMath from 'remark-math'
import rehypeKatexSvelte from "rehype-katex-svelte";

mdsvex({
  remarkPlugins: [
    remarkMath,
  ],
  rehypePlugins: [
    rehypeKatexSvelte,
    /* other rehype plugins... */
  ],
  /* other mdsvex config options... */
});

then add the CSS to the style in src/app.html:

<link rel="stylesheet" 
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
    integrity="sha384-AfEj0r4/OFrOo5t7NnNe46zW/tFgW6x/bCJG8FqQCEo3+Aro6EYUG4+cU+KJWu/X" 
    crossorigin="anonymous">