Render LaTeX in Astro
During the migration of my website to Astro, I needed to be able to render LaTeX for my blog posts. The steps are relatively simple but I wanted to record two quirks during development that was non-obvious (and frustrating):
- If you change the
astro.config.mjs
config file, you need to restart the dev server for changes to take effect - If you change the
markdown
configuration inastro.config.mjs
- specifically theremarkPlugins
orrehypePlugins
arrays, you must make a small edit to your markdown file to trigger reprocessing, even after restarting the dev server. This suggests there is a persistent cache that isn’t invalidated when the config changes.
Having noted that, here are the steps to actually render LaTeX from Markdown in Astro.
-
Install the necessary packages:
bun add remark-math rehype-katex
remark-math
parses LaTeX in Markdown.rehype-katex
renders LaTeX using KaTeX at compile time.
-
Configure Astro to use the
remark-math
andrehype-katex
plugins inastro.config.mjs
:// @ts-check import { defineConfig } from "astro/config"; import rehypeKatex from "rehype-katex"; import remarkMath from "remark-math"; import tailwind from "@astrojs/tailwind"; // https://astro.build/config export default defineConfig({ integrations: [tailwind()], markdown: { remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex], }, });
Remember, you must make a small edit to the markdown file to test for changes.
-
Include KaTeX CSS: Add the following line to the
<head>
of your layout file (e.g.,Layout.astro
) to import the stylesheet:<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-Htz9HMhiwV8GuQ28Xr9pEs1B4qJiYu/nYLLwlDklR53QibDfmQzi7rYxXhMH/5/u" crossorigin="anonymous">
Now you can write LaTeX equations directly in your markdown file, which will be rendered as mathematical equations:
Euler's Identity: $e^{i\pi} + 1 = 0$
Euler’s Identity: