用 Content Collections 管理博客文章,类型安全、结构清晰。
静态博客用 Markdown 写文章、frontmatter 写元数据,大家都这么干。Astro 的 Content Collections 在这上面加了一层:给每类内容定义 schema,Zod 校验,构建时拿到完整的类型提示。
为什么用 Content Collections
配置集中在 content.config.ts,定义 loader 和 schema,页面用 getCollection() / getEntry() 取数据。frontmatter 不符合 schema 直接构建报错,线上不会出现缺字段的情况。过滤也方便——比如本博客用 type: 'tech' | 'essay' 区分技术文和随笔,列表页按类型过滤就行,不用拆两个文件夹。
基本用法
定义 collection 时指定 loader(比如 glob() 指向某个目录)和 schema(Zod 描述 frontmatter 形状)。写文章时在 frontmatter 里填好字段,在页面里:
const posts = await getCollection('posts', ({ data }) => data.type === 'tech');
拿到过滤后的文章,按日期排序、生成列表或详情页。
Content Collections 适合「多篇结构相同的文档」:博客、文档站、项目展示。先想清楚 frontmatter 要哪些字段,再写 schema,后面写内容和做页面都会顺很多。