banner
达达里昂

达达里昂

🇳🇱 | Data Science | Finance | Open Source 没有记录就没有发生。
github

在 Astro .mdx 中的數學排版:使用 remark-math 和 rehype-katex

數學表達式在傳達複雜思想中起著至關重要的作用,尤其是在技術內容中。在這篇博客中,我們將探討如何使用remark-mathrehype-katex這個強大組合,在 Astro 的.mdx 文件中啟用數學排版。

result

步驟 1:📦 安裝套件#

為了開始這個過程,我們需要安裝必要的套件 - remark-mathrehype-katex。打開終端並運行以下命令:

$ npm install remark-math rehype-katex
  • remark-math:這個套件擴展了 Markdown 的功能,使其能夠無縫支援數學表達式。

  • rehype-katex:專為 KaTeX 設計的這個套件以速度和效率處理 Markdown 文件中數學表達式的渲染。

步驟 2:📝 修改 Astro 配置文件#

現在,讓我們修改 Astro 配置文件(astro.config.tsastro.config.mjs)以整合這些套件。按照下面的示例導入並啟用remark-mathrehype-katex

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

export default defineConfig({
	//
	markdown: {
		remarkPlugins: [remarkMath],
		rehypePlugins: [
			[
				rehypeKatex,
				{
					// KaTeX插件選項
				}
			]
		]
	}
})

步驟 3:🪄 在 KaTeX 中使用自動渲染擴展#

為了在整個 HTML 頁面上渲染數學表達式,我們將在 Astro 布局文件的 head 標籤中添加 KaTeX 的自動渲染擴展。在./src/layouts/下找到或創建布局文件。在自動渲染擴展中找到最新的 KaTeX 代碼片段。

<html lang="en" class="scroll-smooth">
	<head>
		<!-- KaTeX -->
		<link
			rel="stylesheet"
			href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
			integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV"
			crossorigin="anonymous"
		/>
		<script
			defer
			src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"
			integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8"
			crossorigin="anonymous"
		></script>
		<script
			defer
			src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"
			integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05"
			crossorigin="anonymous"
			onload="renderMathInElement(document.body);"
		></script>
	</head>

	<body>
		<slot />
	</body>
</html>

✌️ 結論#

使用remark-mathrehype-katex這個強大組合在 Astro 的.mdx 文件中啟用數學排版是一個流暢的過程。這種整合增強了您的內容,使您能夠無縫地包含和美觀地渲染數學表達式,為讀者提供清晰和精確的信息。無論您是技術作者還是處理數學內容的任何人,這種方法都能確保流暢的工作流程和增強的閱讀體驗。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。