0%

hexo-asset-image插件修改

我习惯用Typora来写markdown,默认的hexo-asset-image和Typora的路径方法不太一样,看了一下源码也挺简单,就改成了和Typora相对路径一样的写法。

Typora设置

可以设置插入图片时复制到文件名对应的文件夹:

image-20200407210303642

hexo-asset-image修改

首先设置里的post_asset_folder要打开,然后在 scripts文件夹里新建hexo-asset-image.js文件:

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
34
35
36
37
'use strict';
var cheerio = require('cheerio');

hexo.extend.filter.register('after_post_render', function(data){
const { config } = hexo;
if(config.post_asset_folder){
const link = data.permalink.replace(new RegExp(`^${config.url}/|(index\.html)?$`, 'ig'), "");
console.log(link);
['excerpt', 'more', 'content'].forEach((key) => {
const $ = cheerio.load(data[key], {
ignoreWhitespace: false,
xmlMode: false,
lowerCaseTags: false,
decodeEntities: false
});

$('img').each(function(){
['src', 'data-src'].forEach((srcAttr) => {
if(!$(this).attr(srcAttr)) return
let src = $(this).attr(srcAttr).replace('\\', '/').trim();
// skip http url
if(/^(https?:)?\/\//.test(src)) return
// replace ../ to config.root
if(/^\.\.\//.test(src)) src = src.replace(/^\.\.\//, config.root);
else {
const srcArray = src.split('/').filter((elem) => elem && elem != '.');
if(srcArray.length > 1) srcArray.shift();
src = config.root + link + srcArray.join('/');
}
$(this).attr(srcAttr, src);
console.info&&console.info(`update ${srcAttr} link to:${$(this).attr(srcAttr)}`);
})
});
data[key] = $.html();
});
}
});

代码很简单,分成了三种情况:

  • http://或者//开头的是完整的url地址,不用改
  • ../开头的会定位到上一级目录,也就是source文件夹,替换为config.root
  • 其他的全认为是相对当前文件的地址,用帖子路径去替换和标题相同的第一个文件夹,

要注意的是如果开了NexT主题的lazyloadcontent<img>src会变成data-src,因此要同时检查data-src属性。