Hexo插入图片以及数学公式

Hexo 插入图片

Hexo支持多种插入本地图片的方式,一种是引用绝对路径,一种是引用相对路径。

1. 绝对路径

最简单的方法是将图片统一放到source/images文件夹中,通过markdown语法访问:

1
![](/images/image.jpg)

这种方法,图片在网页的任何位置都可以访问。但是当图片数量较多,这种方法不便于管理。因此推荐下面的方法。

2. 相对路径

除了放在统一的images文件夹,还可以放到文章自己的目录中。文章目录可以通过配置_config.yml来生成。

_config.yml文件中的配置项post_asset_folder设置为true,执行$ hexo new post_name命令时,在source/_posts中会生成和post_name.md同名的文件夹。将图片放入该文件夹下,引用相对路径即可访问图片资源。

上述markdown引用方式,在其他文章和首页中无法显示。

3. CDN引用

除了上述本地图片存储图片,还可以将图片上传CDN服务,如Cloudinary。上传图片后,Cloudinary会生成对应的url地址,可以直接拿来引用。

Hexo 插入TEX数学公式

1. 使用Kramed代替Marked

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

然后,更改/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;
}

2. 停止使用 hexo-math

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

1
npm uninstall hexo-math --save

然后安装 hexo-renderer-mathjax 包:

1
npm install hexo-renderer-mathjax --save

3. 更新 Mathjax 的 CDN 链接

首先,打开/node_modules/hexo-renderer-mathjax/mathjax.html

然后,把<script>更改为:

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>

4. 更改默认转义规则

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

然后,把:

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

更改为:

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

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

更改为:

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

5. 开启mathjax

在主题 _config.yml 中开启 Mathjax, 找到 mathjax 字段添加如下代码:

1
2
mathjax:
enable: true

这一步可选,在博客中开启 Mathjax,, 添加以下内容:

1
2
3
4
5
6
---
title: Testing Mathjax with Hexo
category: Uncategorized
date: 2017/05/03
mathjax: true
---

通过以上步骤,我们就可以在 hexo 中使用 Mathjax 来书写数学公式。

参考文献

https://yanyinhong.github.io/2017/05/02/How-to-insert-image-in-hexo-post/

https://ranmaosong.github.io/2017/11/29/hexo-support-mathjax/