Adding KaTeX for Math in Astro

TeX, LaTeX and KaTex. They sound similar but do different things:

  1. TeX is a typesetting program and programming language created by Donald Knuth back in 1978 to allow anyone to produce high quality books.

  2. LaTeX on the other hand is a software system fo typesetting documents. It was build to provide an easier interface to make writing TeX easier

  3. Finally KaTeX , is a javascript library used to display mathematical notations in web browsers and it’s based on TeX.

Below are some examples:

Einstein’s Mass-Energy Equivalence

E=mc2 E=mc^{2}

Euler’s Identity

eiπ+1=0 e^{i\pi }+1=0

Cauchy momentum equation (convective form)

ρDuDt=p+τ+ρa{\displaystyle \rho {\frac {\mathrm {D} \mathbf {u} }{\mathrm {D} t}}=-\nabla p+\nabla \cdot {\boldsymbol {\tau }}+\rho \,\mathbf {a} }

Linear stress constitutive equation

σ(ε)=pI+λtr(ε)I+2με{\displaystyle {\boldsymbol {\sigma }}({\boldsymbol {\varepsilon }})=-p\mathbf {I} +\lambda \operatorname {tr} ({\boldsymbol {\varepsilon }})\mathbf {I} +2\mu {\boldsymbol {\varepsilon }}}

Stokes’s stress constitutive equation(expression used for incompressible viscous fluids)

τ=μ[u+(u)T]{\displaystyle {\boldsymbol {\tau }}=\mu \left[\nabla \mathbf {u} +(\nabla \mathbf {u} )^{\mathrm {T} }\right]}

Does this blog need this? Probably not. Do I actually understand what any of these formulas mean? Absolutely not.

But this is my playground, and I wanted to figure out how to do it. It turns out implementing KaTeX in Astro is pretty straightforward. We just need two plugins, rehype-katex and rehype-math .

First install the plugins:

npm install remark-math rehype-katex

then update astro.config.mjs to tell Astro’s parser to use this plugins:

import { defineConfig } from "astro/config";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";

export default defineConfig({
  markdown: {
    // remark runs first: parses the math syntax
    remarkPlugins: [remarkMath],
    // rehype runs second: renders the parsed math using KaTeX
    rehypePlugins: [rehypeKatex],
  },
});

Finaly KaTeX needs its stylesheet to render the symbols correctly (otherwise, it’ll just look like broken text). We’ll add this link to our main header component, typically BaseHead.astro or wherever you manage your document’s <head> content.

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/katex@0.16.4/dist/katex.min.css"
  crossorigin="anonymous"
/>

If the equations aren’t rendering properly, the CSS file is almost certainly the culprit (ask me how i know). Make sure that link is loaded.

362 words

© 2023. All rights reserved.