Skip to content
Donghai's Blog
Go back

如何在Astro博客文章中添加LaTeX公式(译)

原文章:How to add LaTeX Equations in Astro blog posts

本文档演示了如何在 AstroPaperMarkdown 文件中使用 LaTeX 公式。LaTeX 是一种强大的排版系统,通常用于数学和科学文档。

Table of contents

Open Table of contents

指南

本节中,你将找到如何在 AstroPaper 的 Markdown 文件中添加 LaTeX 支持的说明。

  1. 通过运行以下命令安装必要的remark和rehype插件:

    pnpm install rehype-katex remark-math katex
  2. 更新Astro配置以使用这些插件:

    // ...
    import remarkMath from "remark-math";
    import rehypeKatex from "rehype-katex";
    
    export default defineConfig({
      // ...
      markdown: {
        remarkPlugins: [
          remarkMath,
          remarkToc,
          [remarkCollapse, { test: "Table of contents" }],
        ],
        rehypePlugins: [rehypeKatex],
        shikiConfig: {
          // For more themes, visit https://shiki.style/themes
          themes: { light: "min-light", dark: "night-owl" },
          wrap: false,
        },
      },
      // ...
    });astro.config.ts
  3. 在主布局文件中导入KaTeX CSS

    ---
    import { SITE } from "@config";
    
    // astro code
    ---
    
    <!doctype html>
    <!-- others... -->
    <script is:inline src="/toggle-theme.js"></script>
    
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/katex@0.15.2/dist/katex.min.css"
    />
    
    <body>
      <slot />
    </body>src/layouts/Layout.astro
  4. 最后一步,在 typography.css 中为 katex 添加文本颜色

@plugin "@tailwindcss/typography";

@layer base {
  /* 其他类 */

  /* KaTeX文本颜色 */
  .prose .katex-display {
    @apply text-foreground;
  }

  /* ===== 代码块和语法高亮 ===== */
  /* 其他类 */
}src/styles/typography.css

完成后,这个设置允许你在 Markdown 文件中编写 LaTeX 公式,并在网站构建时正确渲染。一旦完成,文档的其余部分将正确呈现。


行内公式

行内公式用单个美元符号 $...$ 包裹。以下是一些示例:

  1. 著名的质量-能量等价公式:$E = mc^2$
  2. 二次公式:$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$
  3. 欧拉恒等式:$e^{i\pi} + 1 = 0$

块级公式

For more complex equations or when you want the equation to be displayed on its own line, use double dollar signs $$...$$:

对于更复杂的公式,或者当你希望公式单独显示在一行时,使用双美元符号 $$...$$

高斯积分:

$$ \int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi} $$

黎曼ζ函数的定义:

$$ \zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s} $$

麦克斯韦方程的微分形式:

$$
\begin{aligned}
\nabla \cdot \mathbf{E} &= \frac{\rho}{\varepsilon_0} \\
\nabla \cdot \mathbf{B} &= 0 \\
\nabla \times \mathbf{E} &= -\frac{\partial \mathbf{B}}{\partial t} \\
\nabla \times \mathbf{B} &= \mu_0\left(\mathbf{J} + \varepsilon_0 \frac{\partial \mathbf{E}}{\partial t}\right)
\end{aligned}
$$

使用数学符号

LaTeX提供了丰富的数学符号:


Share this post on:

Previous Post
2024年国庆假期在东北屯子过秋收的一周
Next Post
2024年青岛4天3晚游记
BlogsClub Meo Forever Blog