Hexo 框架 LaTeX 数学公式支持解决方案

问题描述

当前 Hexo 框架的默认 Markdown 渲染器不支持 LaTeX 数学公式语法,导致文章中的数学公式无法正确渲染显示。

解决方案概览

本文档提供三种主要解决方案:

  1. MathJax 集成方案(推荐)
  2. KaTeX 集成方案(性能更好)
  3. 更换渲染器方案(彻底解决)

方案一:MathJax 集成方案(推荐)

1.1 安装 hexo-math 插件

1
npm install hexo-math --save

1.2 配置 _config.yml

在站点根目录的 _config.yml 文件中添加:

1
2
3
4
5
6
7
8
9
10
math:
engine: 'mathjax' # 或者 'katex'
mathjax:
src: https://polyfill.io/v3/polyfill.min.js?features=es6
config:
tex:
inlineMath: [['$', '$'], ['\\(', '\\)']]
displayMath: [['$$', '$$'], ['\\[', '\\]']]
svg:
fontCache: 'global'

1.3 主题配置(以 Butterfly 主题为例)

在主题配置文件 _config.butterfly.yml 中添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Math (数学公式)
math:
# true 表示开启,false 表示关闭
enable: true
# true 表示需要加载 Mathjax/Katex 脚本的页面需要加载
per_page: false
# false 表示不隐藏溢出代码(可以横向滚动)
hide_scrollbar: false
# MathJax
mathjax:
enable: true
# true 表示每一页都加载mathjax.js
# false 表示需要时才加载
per_page: false
# MathJax 的 CDN 地址
CDN: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js

1.4 文章头部配置

在需要使用数学公式的文章头部添加:

1
2
3
4
5
---
title: 计算机图形学
date: 2025-01-15
mathjax: true
---

方案二:KaTeX 集成方案(性能更好)

2.1 安装 hexo-renderer-markdown-it-plus

1
2
npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-markdown-it-plus --save

2.2 配置 _config.yml

markdown_it_plus:
  highlight: true
  html: true
  xhtmlOut: true
  breaks: true
  langPrefix:
  linkify: true
  typographer:
  quotes: '