技术笔记:Astro 内容集合(Content Collections)入门
Astro 的内容集合让你把一堆 Markdown 当作“数据”来管理,还能用 Zod 做字段校验——写错字段会直接报错,非常省心。
定义集合
在 src/content.config.ts 里声明字段:
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(),
date: z.coerce.date(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
}),
});
export const collections = { posts };
读取文章
---
import { getCollection } from 'astro:content';
const posts = await getCollection('posts', ({ data }) => !data.draft);
---
小坑提醒
date用z.coerce.date(),这样在 frontmatter 里写2026-09-15也能自动转成日期对象;draft: true的文章会被上面的过滤条件挡掉,不会出现在列表里。
就这些。内容集合是 Astro 做博客最舒服的地方。