The value of knowledge lies not in possession, but in share.

0%

Hexo中LaTeX公式渲染

在 Hexo 中,无法显示LaTeX数学公式,这对于书写学术博客来说是很大的不便。

以下便是通过安装第三方库来解决这一问题。

安装Kramed代码

Hexo 默认的渲染引擎是 Marked,但是 Marked 不支持 MathjaxKramed 是在 Marked 的基础上进行修改。我们在工程目录下执行以下命令来安装 Kramed.

1
2
npm uninstall hexo-renderer-marked --save
npm install hexo-renderer-kramed --save

然后,更改renderer.js(路径:/node_modules/hexo-renderer-kramed/lib/renderer.js),

更改:

1
2
3
4
5
// Change inline math rule
function formatText(text) {
// Fit kramed's rule: $$ + \1 + $$
return text.replace(/`\$(.*?)\$`/g, '$$$$$1$$$$');
}

为:

1
2
3
4
// Change inline math rule
function formatText(text) {
return text;
}

停止使用 hexo-math

首先,如果你已经安装 hexo-math, 请卸载它:

1
npm uninstall hexo-math --save

然后安装 hexo-renderer-mathjax 包:

1
npm install hexo-renderer-mathjax --save

更新 Mathjax 的 CDN 链接

首先,打开mathjax.html(路径:/node_modules/hexo-renderer-mathjax/mathjax.html)

然后,把<script>更改为:

1
<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

在Marked中更改默认转义规则

因为 Hexo 默认的转义规则会将一些字符进行转义,比如 _ 转为 <em>, 所以我们需要对默认的规则进行修改.
首先, 打开inline.js(路径:node_modules\kramed\lib\rules\inline.js)

1
2
# 第11行
escape: /^\\([\\`*{}\[\]()#$+\-.!_>])/,

更改为:

1
escape: /^\\([`*\[\]()# +\-.!_>])/,

1
2
# 第20行
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,

更改为:

1
em: /^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,

开启mathjax

在主题 _config.yml (路径:/theme/next/_config.yml)中开启 Mathjax,

找到 mathjax 字段修改如下代码(false改为true):

1
2
mathjax:
enable: true

在文章的Front-matter里打开Mathjax开关

1
2
3
4
5
6
7
---
title: Hexo中LaTeX公式渲染
date: 2018-03-25 16:10:25
tags: [Markdown, LaTeX, Hexo]
categories: Hexo
mathjax: true
---

测试

LaTeX源码:

1
2
3
4
5
6
\begin{eqnarray}
\nabla\cdot\vec{E} &=& \frac{\rho}{\epsilon_0} \\
\nabla\cdot\vec{B} &=& 0 \\
\nabla\times\vec{E} &=& -\frac{\partial B}{\partial t} \\
\nabla\times\vec{B} &=& \mu_0\left(\vec{J}+\epsilon_0\frac{\partial E}{\partial t} \right)
\end{eqnarray}

显示效果,如下所示:

可以正常显示麦克斯韦方程组。

🍭支持一根棒棒糖吧!