Astro 5 的内容集合
Astro 5 的内容集合用 glob loader 取代了旧的目录约定,schema 用 zod 校验 frontmatter。喵~
定义集合
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const posts = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
schema: z.object({
title: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
}),
});
export const collections = { posts };
读取与渲染
getCollection('posts')拿到所有条目。render(entry)得到<Content />组件用于渲染正文。
这样 frontmatter 写错了,构建期就会报错,而不是上线后才发现文章页空白。
小结
类型安全 + 构建期校验 = 主题能放心交给别人用。喵~