Astro Content Collections 入门
理解 Astro v5+ 新版 Content Collections API,包括 loader 和 Zod schema。
Astro Content Collections 入门
Astro v5 起,Content Collections 引入了新的 loader 模式,让数据来源更灵活。
核心三件事
- Collection 定义 ——
src/content.config.ts - Schema 校验 —— 用 Zod 描述 frontmatter 形状
- 数据查询 —— 在
.astro文件里await getCollection('blog')
例子
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
export const collections = { blog };
渲染一篇文章
---
import { getCollection, render } from 'astro:content';
const posts = await getCollection('blog');
const { Content } = await render(posts[0]);
---
<article>
<h1>{posts[0].data.title}</h1>
<Content />
</article>
为什么用 v5+ 新 API
- 支持非文件系统数据源(CMS、API、数据库)
- Schema 校验与 collection 定义解耦
- 自动生成 TypeScript 类型