Astro Content Collections 入门
用 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,后面写内容和做页面都会很顺。