知乎上的《在 Astro 中显示数学公式》(2023) 一文所使用的方法,已不再适配最新版本的 Astro。

本文内容与知乎原文大体相同,唯一区别在于 Markdown 插件的配置方式。

安装依赖

本文假设你使用 Node.js。在项目根目录下打开终端,执行以下命令:

npm install remark-math rehype-katex katex

编辑 Astro 配置

修改项目根目录下的 astro.config.mjs(或 .js / .ts)文件,按以下方式添加 Markdown 插件:

import { defineConfig } from 'astro/config';
import { unified } from '@astrojs/markdown-remark';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
// ...... 其他导入

export default defineConfig({
  // ...... 其他配置
  markdown: {
    processor: unified({
      remarkPlugins: [remarkMath],
      rehypePlugins: [rehypeKatex],
    }),
  },
  // ...... 其他配置
});

添加 CSS 文件

为了让公式正确显示样式,需要在博客的通用模板中引入 KaTeX 的 CSS 文件。例如,在 Layout.astro 组件中添加:

import "katex/dist/katex.min.css";

请确保所有由 Markdown 生成的页面都能访问到这个 CSS 文件。

关于如何组织全局 Head 组件,可参考 Astro 官方配置指南

关键变化说明

本文与知乎原文的唯一区别在于 Markdown 插件的导入方式。新旧写法对比如下:

新写法:

import { unified } from '@astrojs/markdown-remark';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';

export default defineConfig({
  markdown: {
    processor: unified({
      remarkPlugins: [remarkMath],
      rehypePlugins: [rehypeKatex],
    }),
  },
});

旧写法(知乎原文,已不适用):

export default defineConfig({
  markdown: {
    remarkPlugins: [remarkMath],   // 已弃用,无法正常工作
    rehypePlugins: [rehypeKatex], // 编译时会发出警告,公式也不会被渲染
  },
});

如果需要改变 shiki 主题,可以这样写:

import { unified, rehypeShiki } from '@astrojs/markdown-remark';
// ......
export default defineConfig({
  // ......
  markdown: {
    processor: unified({
      remarkPlugins: [remarkMath],
      rehypePlugins: [
        rehypeKatex,
        [rehypeShiki, { theme: 'dark-plus' }], // 使用重导出的 rehypeShiki
      ],
    }),
  },
  // ......
});

补充说明

在导入 KaTeX 样式时,"/node_modules/" 前缀是可选的——因为 katex 已作为项目依赖安装,可以直接通过包名引用:

// 以下两种写法均可
import "katex/dist/katex.min.css";
import "/node_modules/katex/dist/katex.min.css";