本页导航
article
自动生成frontmatter
AI摘要
vitepress-plugin-setfrontmatter 是一个专为 VitePress 设计的插件,能自动为 Markdown 文件生成和管理 frontmatter,支持自定义扩展和排除规则。通过简单配置和代码示例,用户可以轻松集成该插件,实现文档元数据的自动维护,提升开发效率和文档质量
vitepress-plugin-setfrontmatter使用
github地址
✨ 特性
- ✨ 自动为Markdown文件添加缺失的frontmatter字段(标题、日期、永久链接等)
- 🔄 支持自定义frontmatter转换函数
- 📁 支持自动生成基于文件路径的分类信息
- 🗑️ 支持删除指定的frontmatter字段
- 🌐 兼容VitePress的国际化配置
安装
安装 vitepress-plugin-setfrontmatter
插件
使用方法
在VitePress配置文件中引入并使用插件
说明:该插件仅限项目启动时生效。
- 插件默认忽略 frontmatter 中 layout: home 和 [“node_modules”, “dist”] 目录下的文件,且只扫描 Markdown 文档。
- 插件默认给 Markdown 文件生成 title 和 date 两个属性,其中 title 为文件名(支持带序号的文件名,如 01.xx.md),date 为文件的创建日期,urlPrefix和categories选项都是可选的,如果想拓展 frontmatter 的内容,则使用
transform
函数。
transform详细说明
自定义转换frontmatter的函数。该函数接收两个参数:当前的frontmatter对象和文件信息对象。
transform: (frontmatter) => {
// 添加自定义字段
return {
...frontmatter,
author: 'Your Name',
tags: ['vitepress', 'plugin']
}
}
如果函数返回一个对象,该对象将作为新的frontmatter;如果返回undefined
,则使用原frontmatter;如果返回空对象{}
,则清空原有frontmatter,下面展示了一个例子,根据文件路径添加标签
import { defineConfig } from 'vitepress'
import AutoFrontmatter from 'vitepress-plugin-setfrontmatter'
export default defineConfig({
vite: {
plugins: [
AutoFrontmatter ({
pattern: '**/*.md',
transform: (frontmatter, fileInfo) => {
// 根据文件路径添加标签
const tags = []
if (fileInfo.relativePath.includes('vue')) {
tags.push('vue')
}
if (fileInfo.relativePath.includes('react')) {
tags.push('react')
}
return {
...frontmatter,
tags,
lastUpdated: new Date().toISOString()
}
}
})
]
}
})
配置选项
选项 | 类型 | 默认值 | 描述 |
---|---|---|---|
pattern |
string | string[] |
- | 扫描的文件路径表达式,使用glob语法 |
globOptions |
GlobOptions |
- | tinyglobby的配置项,插件默认已忽略node_modules和dist目录 |
urlPrefix |
string |
- | 永久链接前缀,如设置为"/pages/",生成的url为"/pages/xxxx",不设置则不会生成永久链接 |
categories |
boolean |
false |
是否启用自动添加frontmatter.categories功能 |
key |
string |
"coverImg" |
要从frontmatter中删除的键名,coverImg配置为false并且key存在于frontmatter生效 |
coverImg |
boolean |
false |
是否启用自动添加frontmatter.coverImg功能 |
transform |
Function |
- | 自定义转换frontmatter的函数 |
工作原理
插件会在VitePress构建过程中扫描指定的Markdown文件,并执行以下操作:
- 读取文件内容并解析现有的frontmatter
- 如果缺少标题,则根据文件名自动生成
- 如果缺少日期,则使用文件创建时间
- 如果设置了urlPrefix,则生成唯一的永久链接
- 如果启用了categories功能,则根据文件路径生成分类信息
- 如果提供了transform函数,则使用该函数进一步处理frontmatter
- 将处理后的frontmatter写回文件
最后更新于 2025-10-02 15:52