跳转到内容
文韬博宇的个人主页
返回

【转载】如何在 Astro 博客文章中添加 LaTeX 公式

更新于:
· 约 1 分钟· 约 314 字阅读0编辑页面

本文演示了如何在 AstroPaper 的 Markdown 文件中使用 LaTeX 公式。LaTeX 是一款强大的排版系统,广泛用于数学和科学类文档。

Free Close-up of complex equations on a chalkboard, showcasing chemistry and math symbols. Stock Photo
照片来源:Vitaly Gariev

目录

操作步骤

本节将介绍如何在 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>
    <!-- Other elements  -->
    <meta property="og:image" content={socialImageURL} />
    
    <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 {
      /* other classes */
    
      /* Katex text color */
      .prose .katex-display {
        @apply text-foreground;
      }
    
      /* ===== Code Blocks & Syntax Highlighting ===== */
      /* other classes */
    }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$

独立公式块

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

高斯积分:

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

黎曼 zeta 函数的定义:

$$ \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 提供了丰富的数学符号:


编辑页面
分享这篇文章:

评论


上一篇
【转载】自定义 AstroPaper 主题配色方案