Byteli

Math Typesetting in Astro .mdx: Using remark-math & rehype-katex

Photo by Artturi Jalli on Unsplash

Mathematical expressions play a crucial role in conveying complex ideas, especially in technical content. In this blog, we’ll explore how to enable math typesetting in Astro .mdx files using the powerful combination of remark-math and rehype-katex.

astro_with_math_typesetting

Step 1: Package installation

To kickstart the process, we need to install the necessary packages – remark-math and rehype-katex. Open your terminal and run the following command:

1$ npm install remark-math rehype-katex

Step 2: Modifying the Astro config file

Now, let’s modify the Astro config file (astro.config.ts or astro.config.mjs) to incorporate these packages. Import and enable remark-math and rehype-katex as shown below:

 1import { defineConfig } from 'astro/config'
 2import remarkMath from 'remark-math'
 3import rehypeKatex from 'rehype-katex'
 4
 5export default defineConfig({
 6	//
 7	markdown: {
 8		remarkPlugins: [remarkMath],
 9		rehypePlugins: [
10			[
11				rehypeKatex,
12				{
13					// Katex plugin options
14				}
15			]
16		]
17	}
18})

Step 3: Use Auto-render Extension in Katex

To render math across the entire HTML page, we’ll add the Auto-render Extension of KaTeX in the head tag of our Astro layout file for Markdown pages. Locate or create the layout file under ./src/layouts/. Find the latest Katex code snippet on Auto-render Extension.

 1<html lang="en" class="scroll-smooth">
 2	<head>
 3		<!-- Katex -->
 4		<link
 5			rel="stylesheet"
 6			href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css"
 7			integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV"
 8			crossorigin="anonymous"
 9		/>
10		<script
11			defer
12			src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"
13			integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8"
14			crossorigin="anonymous"
15		></script>
16		<script
17			defer
18			src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"
19			integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05"
20			crossorigin="anonymous"
21			onload="renderMathInElement(document.body);"
22		></script>
23	</head>
24
25	<body>
26		<slot />
27	</body>
28</html>

Conclusion

Enabling math typesetting in Astro .mdx files is a streamlined process with the powerful combination of remark-math and rehype-katex. This integration enhances your content, allowing you to seamlessly include and beautifully render mathematical expressions, providing clarity and precision to your readers. Whether you’re a technical author or anyone dealing with mathematical content, this approach ensures a smooth workflow and an enhanced reading experience.

#frontend #astro


Reply to this post by email ↪