Hexo无法跳过yml文件渲染的解决方法

胡永双 Lv3
  • 问题根源:Hexo会把.yml/.yaml文件识别为数据文件(Data Files),这类文件会被Hexo主动解析并加入到模板变量site.data中,这个过程发生在skip_render生效之前,所以即使配置了skip_render,Hexo依然会先解析.yml文件,再尝试跳过渲染(但解析过程已经完成)。
  • 解决方法:利用脚本强制复制yml文件到public目录。在Hexo根目录创建一个scripts文件夹,在文件夹里创建一个名为copy-yaml.js的JavaScript文件,并将下面的代码写入。或者点击 下载 copy-yaml.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
38
39
40
41
42
43
44
45
46
47
48
49
50
'use strict';

const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');

// 确保 YAML 文件被复制到 public 目录
hexo.extend.filter.register('after_generate', function() {
console.log('开始处理 YAML 文件复制...');

const sourceDir = hexo.source_dir;
const publicDir = hexo.public_dir;

// 查找所有 YAML 文件
function findAndCopyYamlFiles(dir, basePath = '') {
const files = fs.readdirSync(dir);

files.forEach(file => {
const fullPath = path.join(dir, file);
const relativePath = path.join(basePath, file);
const stat = fs.statSync(fullPath);

if (stat.isDirectory()) {
// 递归处理子目录
findAndCopyYamlFiles(fullPath, relativePath);
} else if (file.match(/\.(yml|yaml)$/i)) {
// 处理 YAML 文件
const destDir = path.join(publicDir, basePath);
const destPath = path.join(destDir, file);

// 确保目标目录存在
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}

// 复制文件
try {
fs.copyFileSync(fullPath, destPath);
console.log(`已复制: ${relativePath} -> ${path.relative(publicDir, destPath)}`);
} catch (err) {
console.error(`复制失败: ${relativePath}`, err.message);
}
}
});
}

// 从 source 目录开始查找
findAndCopyYamlFiles(sourceDir);
console.log('YAML 文件复制完成');
});
  • 最后在_config.yml配置文件中修改下面的配置。
1
2
exclude:
- "Path" # yml文件存放路径
  • 标题: Hexo无法跳过yml文件渲染的解决方法
  • 作者: 胡永双
  • 创建于 : 2024-11-11 15:42:51
  • 更新于 : 2024-11-15 12:07:36
  • 链接: https://huyongshuang.github.io/2024/11/11-copy-yaml/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
Hexo无法跳过yml文件渲染的解决方法