Qwik MDX math support

Introduction

Qwik MDX supports math expressions using KaTeX with some configuration. The installation is fairly easy. This guide is assuming that you already have got a Qwik CLI application running. At first you need to install two packages:

npm i remark-math
npm i rehype-katex

Then you need to open the vite.config.ts file in the root directory. There you need to add the following object to the qwikCity vite configuration function as a parameter and keep the rest of the file untouched.

import { defineConfig } from 'vite';
import { qwikVite } from '@builder.io/qwik/optimizer';
import { qwikCity } from '@builder.io/qwik-city/vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import rehypeKatex from 'rehype-katex';
import remarkMath from 'remark-math';

export default defineConfig(() => {
  return {
    plugins: [
      qwikCity({
        mdx: {
          remarkPlugins: [remarkMath],
          rehypePlugins: [rehypeKatex],
        },
      }),
      qwikVite(),
      tsconfigPaths(),
    ],
  };
});

Your Vite might not compile because it complains about rehype-katex's ESM requirement. You can make it run by adding {"type": "module"} to your package.json file. Last but not least you need to copy KaTeX's CSS file into your project. You can find it in the katex/dist/katex.min.css file in your node_modules. Create a new file next to your root.tsx file and name it katex.css. Then copy the contents of the KaTeX CSS file into it. Open the root.tsx file and import the CSS file in the imports section with import './katex.css';. And voilà! You can now use math in your posts.

Usage

You can use it in your Qwik MDX files by wrapping your math in $$:

$$
\begin{aligned}
  f(x) = a * x + b
\end{aligned}
$$

Which will render as:

f(x)=ax+b\begin{aligned} f(x) = a * x + b \end{aligned}

or with a single dollar sign to inline the expression.

Cover Photo by Jeswin Thomas on Unsplash