如何在Jekyll项目构建阶段运行基础测试?含frontmatter测试示例
在Jekyll构建阶段运行基础测试的方法
一、用Jekyll钩子直接测试内容
Jekyll自带Ruby钩子机制,能在构建的不同阶段(比如文章初始化、构建完成后)执行自定义代码,适合直接校验frontmatter变量或生成内容。
示例:统计frontmatter指定字段的单词数
- 在项目根目录创建
_plugins/test_frontmatter.rb文件(Jekyll会自动加载插件目录下的Ruby文件) - 写入以下代码:
Jekyll::Hooks.register :posts, :post_init do |post| # 统计frontmatter里`description`字段的单词数 if post.data.key?('description') desc = post.data['description'].strip word_count = desc.split(/\s+/).size puts "文章 #{post.slug}:description单词数为 #{word_count}" # 可选:单词数不达标就终止构建 if word_count < 10 raise "文章 #{post.slug}的description单词数不足10个,当前为#{word_count}" end else puts "文章 #{post.slug}缺少description字段" end end
这段代码会在每篇文章初始化后,自动检查description的单词数,控制台输出结果,还能设置阈值,不满足就中断构建流程。
二、构建后测试生成的HTML文件
如果要校验最终输出的HTML内容,可在post_build钩子中读取_site目录下的文件,用Ruby的解析库(比如Nokogiri)检查内容。
示例:检查HTML标题是否匹配文章标题
require 'nokogiri' Jekyll::Hooks.register :site, :post_build do |site| site.posts.docs.each do |post| html_path = site.in_dest_dir(post.url.sub(/^\//, '')) + 'index.html' if File.exist?(html_path) doc = Nokogiri::HTML(File.read(html_path)) page_title = doc.css('title').text unless page_title.include?(post.data['title']) raise "文章 #{post.slug}的HTML标题不匹配,预期包含#{post.data['title']},实际为#{page_title}" end end end end
三、用外部脚本配合构建命令
如果不想写Ruby插件,也可以用Python/Node.js等脚本在构建前后执行,比如:
- 若用npm管理项目,修改
package.json添加脚本:
{ "scripts": { "test:frontmatter": "python scripts/check_frontmatter.py", "build": "jekyll build && npm run test:frontmatter" } }
- 编写
scripts/check_frontmatter.py脚本,遍历_posts目录解析frontmatter:
import yaml import os import re def count_words(text): return len(re.findall(r'\w+', text)) posts_dir = '_posts' for filename in os.listdir(posts_dir): if filename.endswith('.md'): filepath = os.path.join(posts_dir, filename) with open(filepath, 'r', encoding='utf-8') as f: content = f.read() if content.startswith('---'): end_idx = content.find('---', 3) if end_idx != -1: frontmatter = yaml.safe_load(content[3:end_idx]) if 'description' in frontmatter: word_count = count_words(frontmatter['description']) print(f"文章 {filename}:description单词数为 {word_count}") if word_count < 10: raise Exception(f"文章 {filename}的description单词数不足10个")
之后运行npm run build,就会先完成Jekyll构建,再执行测试脚本。
内容的提问来源于stack exchange,提问作者user1086516
相关产品推荐
相关产品推荐

