Abstract: 用 `hexo-renderer-markdown-it`,搭配 KaTeX 使 Hexo 博客支持 LaTeX 语法渲染。

本文由上上篇文章而来(
废话不多说,直接上干货。

1. 替换渲染引擎

1.1 删除 Hexo 原有渲染引擎

Hexo 原使用 hexo-renderer-marked 作为 Markdown 渲染引擎。
在 Hexo 根目录运行:

1
npm un hexo-renderer-marked --save

1.2 安装新引擎

用 hexo-renderer-markdown-it ,搭配 @renbaoshuo/markdown-it-katex 来解决。
继续在 Hexo 根目录运行:

1
npm i hexo-renderer-markdown-it katex @renbaoshuo/markdown-it-katex --save

2. 修改配置

2.1 Hexo 配置修改

在 Hexo 根目录找到 _config.yml,末尾添加解析规则:

1
2
3
4
5
6
7
8
9
10
11
12
markdown:
render:
html: true
xhtmlOut: false
breaks: true
linkify: true
typographer: false # 防止双引号或破折号被意外转义
plugins:
- name: '@renbaoshuo/markdown-it-katex'
options:
strict: false
skipDelimitersCheck: true # 允许 $ 符号与内容之间存在空格(容错性更高)

2.2 主题配置修改

在主题目录中打开 _config.yml (./themes/[YOUR_THEME]/_config.yml),找到 math 或 katex 相关配置项(Ctrl + F 搜索)
以下以 Butterfly 为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Math (數學)

# --------------------------------------

# About the per_page

# if you set it to true, it will load mathjax/katex script in each page (true 表示每一頁都加載js)

# if you set it to false, it will load mathjax/katex script according to your setting (add the 'mathjax: true' in page's front-matter)

# (false 需要時加載,須在使用的 Markdown Front-matter 加上 mathjax: true)



# MathJax

mathjax:

  enable: false

  per_page: false



# KaTeX

katex:

  enable: true # 此处将 false 修改为 true

  per_page: false # 保持 false 以关闭全局渲染,减少其他文章加载时间

  hide_scrollbar: true

3. 按需开启

需要在某一篇文章里启用 LaTeX 渲染时,在其 .md 文件开头 Front-matter 中添加启用即可。

1
2
3
4
5
6
---
title: 我的公式文章
katex: true
---

这是一个行内公式:$a^2 + b^2 = c^2$