您的位置:首页 > 新闻 > 会展 > Typora + Hexo 图片路径问题(Typedown)

Typora + Hexo 图片路径问题(Typedown)

2024/10/17 11:27:31 来源:https://blog.csdn.net/m0_51390969/article/details/139906818  浏览:    关键词:Typora + Hexo 图片路径问题(Typedown)

文章目录

  • 1. 冲突来源
  • 2. 解决思路
  • 3. 实现
    • 1. typora图片路径
    • 2. hexo脚本

1. 冲突来源

Hexo上对于图片在md中的引用,使用了post_asset_folder: true配置,来更好的管理图片。
当一篇名为xxx.md的文章引用1.png图片时,默认让1.png保持在xxx文件夹下,那么md中即可使用{% asset_img 1.png %}来引用图片。

而typora中,或者Typedown中,复制图片时,一般使用![](./xxx/1.png)

2. 解决思路

  1. 让每次图片复制到md时,typora都能将其自动放入和md文件同名同级文件夹下。
  2. 然后在Hexo编译前使用脚本将![](./xxx/1.png)转化为{% asset_img 1.png %},并且保持md源文件不变。

3. 实现

1. typora图片路径

在这里插入图片描述

这很简单。

但是如果你是typedown就会发现,不支持解析${filename},那么只有每次写的时候手动选择同级同名文件夹了。

2. hexo脚本

scripts\before_generate.js中写入

// const path = require('path');// hexo.extend.filter.register('before_post_render', data => {
//   if (data.layout === 'post') {
//     const postName = path.basename(data.source, '.md');
//     const imgRegex = new RegExp(`!\\[.*?\\]\\(\\.\\/${postName}\\/([^\\)]+)\\)`, 'g');//     data.content = data.content.replace(imgRegex, (match, p1) => {
//       return `{% asset_img ${p1} %}`;
//     });
//   }
//   return data;
// });const path = require('path');hexo.extend.filter.register('before_post_render', data => {if (data.layout === 'post') {const postName = path.basename(data.source, '.md');const imgRegex = new RegExp(`!\\[.*?\\]\\(\\.\\/${postName}\\/([^\\)]+)\\)`, 'g');// 原始内容const originalContent = data.content;// 转换内容let match;let modifiedContent = originalContent;while ((match = imgRegex.exec(originalContent)) !== null) {const originalLine = match[0];const newLine = `{% asset_img ${match[1]} %}`;// 打印转换前后的对比console.log(`Original line: ${originalLine}`);console.log(`Converted line: ${newLine}\n`);// 进行替换modifiedContent = modifiedContent.replace(originalLine, newLine);}// 更新数据内容data.content = modifiedContent;}return data;
});

被注释掉了是不会打印日志对比前后修改的,没注释的会。

执行hexo cleanhexo generate,然后hexo server看看效果。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com