Astro Content Collections 完全指南
深入了解 Astro 5 的 Content Collections API,如何高效管理 MDX 内容。
Astro 的 Content Collections 是管理站点内容的最佳方式之一。本文将详细介绍如何使用它。
为什么需要 Content Collections?
传统的文件读取方式容易出错,而 Content Collections 提供了:
- 类型安全:自动验证 frontmatter
- 更好的 IDE 支持:完整的类型推断
- 内置查询:方便的获取和过滤
定义 Collection
在 src/content/config.ts 中定义 schema:
import { defineCollection, z } from 'astro:content';
const posts = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
查询内容
const posts = await getCollection('posts');
const filtered = posts.filter(post => post.data.tags.includes('Astro'));
Content Collections 让内容管理变得优雅且可靠。