1、问题

使用Typora+Hexo搭建本地博客时出现图片无法在网页上查看

2、问题分析

相对路径从md格式解析为html出现错误

3、问题解决

(1) 先确定使用的渲染器是hexo-renderer-marked

打开./package.json文件,确认当前安装并启用的渲染插件是hexo-renderer-marked

没有就运行以下命令安装

1
npm install hexo-renderer-marked

(2) 设置中开启附件文件夹

./_config.yml中设置如下:

1
2
3
4
5
post_asset_folder: true
relative_link: false
marked:
prependRoot: true
postAsset: true

(3)修改render.js

  • 这一步是为了能够使图片在Typora和网页上都能查看

  • 附件位置在渲染时默认它在与文章同名同级文件夹下,解析为Html时会自动加上文章同名文件夹的路径

  • 如果此时在Markdown下使用文章名/图片.jpg插入图片,那么解析成Html时路径会变成xxx/文章名/文章名/图片.jpg,造成无法在网页显示。如果牺牲Typora的预览,插入路径设为![](图片.jpg)这样在Typora无法预览,此时在网页可以查看,两全其美的办法时修改渲染器render.js下附件目录

  • 打开./node_modules/hexo-renderer-marked/lib/renderer.js,搜索image定位到修改图片相对路径的代码

image-20250312061524120

我的路径如下:

1
H:\Blog\Hexo_Local\node_modules\hexo-renderer-marked\lib\renderer.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
    // Prepend root to image path
    image(href, title, text) {
    const { hexo, options } = this;
    const { hexo图片相对路径无法显示问题_link } = hexo.config;
    const { lazyload, figcaption, prependRoot, postPath } = options;

    if (!/^(#|\/\/|http(s)?:)/.test(href) && !hexo图片相对路径无法显示问题_link && prependRoot) {
    if (!href.startsWith('/') && !href.startsWith('\\') && postPath) {
    const PostAsset = hexo.model('PostAsset');
    // findById requires forward slash

    // ============================== 以下代码有改动 ==============================
    const fixPostPath = join(postPath, '../');
    const asset = PostAsset.findById(join(fixPostPath, href.replace(/\\/g, '/')));
    // const asset = PostAsset.findById(join(postPath, href.replace(/\\/g, '/')));
    // ============================== 以上代码有改动 ==============================

    // asset.path is backward slash in Windows
    if (asset) href = asset.path.replace(/\\/g, '/');
    }
    href = url_for.call(hexo, href);
    }

    let out = `<img src="${encodeURL(href)}"`;
    if (text) out += ` alt="${text}"`;
    if (title) out += ` title="${title}"`;
    if (lazyload) out += ' loading="lazy"';

    out += '>';
    if (figcaption) {
    if (text) out += `<figcaption aria-hidden="true">${text}</figcaption>`;
    }
    return out;
    }
    这里的修改就是将文章路径postPath换成了它的上一级路径fixPostPath,更换的方法就是在postPath后面加上../

一些尝试

  • 这样操作后图片只能存放在和文章同名的文件夹,没有自由度,打算更改图片存放路径,在Blog\Hexo_Local\node_modules\hexo\dist\hexo\post.js找到相关代码段,但是发现修改后不起作用,推测还需要修改js文件映射出的map文件,即重新编译

  • 下载hexo工程后在和上述post.js对应的ts文件中修改,重新在hexo项目根目录运行本地安装

    1
    npm install 
  • 发现在hexo init 时node_module仍然是从网上下载的,即在post.ts修改仍然不起作用,遂搁置

    代码片段如下:

image-20250313021526937

本地路径:

1
H:\Blog\Hexo_Local\node_modules\hexo\dist\hexo\post.js

Ref

如何进入指定文件目录_hexo博客如何插入图片-CSDN博客

Hexo 图片设置相对路径 | AI悦创-Python一对一辅导

Hexo插入图片并解决图片的路径问题 | Lucien的博客