Adding KaTeX for Math in Astro
TeX, LaTeX and KaTex. They sound similar but do different things:
-
TeX is a typesetting program and programming language created by Donald Knuth back in 1978 to allow anyone to produce high quality books.
-
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
-
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
Euler’s Identity
Cauchy momentum equation (convective form)
Linear stress constitutive equation
Stokes’s stress constitutive equation(expression used for incompressible viscous fluids)
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.