5月27日 21:07

什么是 Astro 的内容集合(Content Collections)?如何使用它来管理博客文章或文档?

Astro 内容集合是什么

Astro 内容集合(Content Collections)是 Astro 内置的结构化内容管理方案,把散落在项目里的 Markdown、MDX、JSON 等文件统一收进 src/content/ 目录,用 Zod Schema 做 frontmatter 校验,构建时自动完成类型推断和验证——写错字段名直接报编译错误,不用等到线上才发现。

怎么用

两步走:定义 Schema,写内容文件。

src/content/config.ts 里声明集合:

typescript
import { defineCollection, z } from 'astro:content'; const blog = defineCollection({ schema: z.object({ title: z.string(), date: z.coerce.date(), tags: z.array(z.string()), }), }); export const collections = { blog };

然后在 src/content/blog/ 下创建 Markdown 文件,frontmatter 必须符合 schema 定义,否则构建失败。

页面里用 getCollection 批量查询,用 getEntry 按 slug 取单条:

astro
--- import { getCollection, getEntry } from 'astro:content'; const posts = await getCollection('blog'); const post = await getEntry('blog', 'my-post'); const { Content } = await post.render(); --- <Content />

动态路由配合 getStaticPaths 就能自动生成所有文章页面。

追问:和直接在 pages 目录放 Markdown 有什么区别

没有内容集合时,每个 Markdown 文件就是一个路由,frontmatter 没有任何校验——title 拼成 titel 不会报错,日期格式不对也不会拦你。集合的核心价值就是构建时校验 + 类型安全getCollection 返回的数据有完整的 TypeScript 类型,IDE 自动补全直接可用。

追问:一个项目能定义多个集合吗

可以。config.ts 里 export 多个集合就行,博客一个、文档一个、产品数据一个,各自独立的 schema,互不干扰。数据型内容(JSON/YAML)用 type: 'data',文本型(Markdown/MDX)用 type: 'content'

追问:内容集合有什么局限

内容集合是构建时处理的,不支持运行时动态添加内容。如果你的站点需要用户投稿或实时更新内容,得搭配 Headless CMS 或数据库,集合只负责静态内容的类型安全。

标签:Astro