Skip to content

在 VitePress 中 渲染数学公式

在撰写技术文档或学术笔记时,我们经常需要在 Markdown 中插入数学公式。 VitePress 原生支持 Markdown,但不支持 LaTeX 语法的公式渲染。 为了解决这个问题,我们可以借助 markdown-it-mathjax3 插件,在 VitePress 中优雅地渲染数学公式。


一、背景与原理

VitePress 的 Markdown 渲染基于 markdown-it。 因此,如果我们想扩展 Markdown 的语法功能,只需要引入相应的 markdown-it 插件即可。

markdown-it-mathjax3 就是一个专门用于在 Markdown 文件中渲染 LaTeX 数学公式的插件,它基于 MathJax v3 实现,支持行内与块级公式两种形式:

  • 行内公式:$E = mc^2$

  • 块级公式:

    latex
    $$
    \int_0^{\infty} e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}
    $$

二、安装依赖

在你的 VitePress 项目中执行以下命令安装插件:

bash
pnpm add markdown-it-mathjax3 -D

如果使用 npm 或 yarn,也可以:

bash
npm install markdown-it-mathjax3 --save-dev
# 或者
yarn add markdown-it-mathjax3 -D

三、配置 VitePress

.vitepress/config.ts(或 config.js)中添加如下配置:

ts
import { defineConfig } from 'vitepress';
import mathjax3 from 'markdown-it-mathjax3';

const customElements = [
  'mjx-container',
  'mjx-assistive-mml',
  'math',
  'maction',
  'maligngroup',
  'malignmark',
  'menclose',
  'merror',
  'mfenced',
  'mfrac',
  'mi',
  'mlongdiv',
  'mmultiscripts',
  'mn',
  'mo',
  'mover',
  'mpadded',
  'mphantom',
  'mroot',
  'mrow',
  'ms',
  'mscarries',
  'mscarry',
  'msgroup',
  'msline',
  'msrow',
  'mspace',
  'msqrt',
  'mstack',
  'mstyle',
  'msub',
  'msup',
  'msubsup',
  'mtable',
  'mtd',
  'mtext',
  'mtr',
  'munder',
  'munderover',
  'semantics',
  'annotation',
  'annotation-xml',
];

export default defineConfig({
  markdown: {
    config: (md) => {
      md.use(mathjax3);
    },
  },
  vue: {
    template: {
      compilerOptions: {
        // 让 Vue 识别 MathJax 生成的自定义标签
        isCustomElement: (tag) => customElements.includes(tag),
      },
    },
  },
});

说明:

  • markdown-it-mathjax3 会在渲染时生成大量的 MathML 标签(如 <mjx-container> 等)。
  • Vue 默认会对这些未知标签进行警告,因此需要通过 isCustomElement 告诉 Vue 忽略它们。

四、测试效果

在你的 Markdown 文件中添加如下内容进行测试:

markdown
行内公式示例:爱因斯坦质能方程 $E = mc^2$

块级公式示例:

$$
\int_0^{\infty} e^{-x^2}\,dx = \frac{\sqrt{\pi}}{2}
$$

构建后你应该能看到正确渲染的数学公式,如下:

0ex2dx=π2