模式验证器
使用验证器定义内容集合 schema,并获得更稳定的内容结构。
Nuxt Content 支持为集合定义 schema。schema 可以约束 frontmatter 字段、减少内容录入错误,并让查询结果拥有更清晰的类型。
使用 Zod
项目可以使用 Zod 定义集合字段:
import { defineCollection, defineContentConfig } from '@nuxt/content'
import { z } from 'zod'
export default defineContentConfig({
collections: {
blog: defineCollection({
type: 'page',
source: 'blog/**/*.md',
schema: z.object({
title: z.string(),
description: z.string().optional(),
date: z.string(),
category: z.string().optional(),
tags: z.array(z.string()).optional()
})
})
}
})
为什么需要 schema
schema 能帮助团队在内容层提前发现问题:
- 标题、日期等必填字段缺失。
- 字段类型不一致,例如
tags写成字符串。 - 内容列表需要排序但日期格式不稳定。
- 页面 SEO 依赖的描述字段为空。
常见字段
| 字段 | 类型 | 用途 |
|---|---|---|
title | string | 页面标题 |
description | string | SEO 描述和列表摘要 |
date | string | 发布时间或更新日期 |
category | string | 分类 |
tags | string | 标签 |
image | string | 封面图 |
使用建议
- 先为公开页面内容补齐基础 schema,再逐步扩展复杂字段。
- 对数组、日期、图片等容易写错的字段增加校验。
- schema 不应过度复杂,避免内容维护成本过高。
- 修改 schema 后,应运行类型检查和静态生成,确认所有内容仍能通过解析。
