在给自己的个人站添加人文和技术两个内容板块时, 需要一套能同时管理两种文章的内容系统。 Astro 的 Content Collections 正好解决这个问题。
为什么选 Content Collections
不用 Content Collections 的话,文章散落在 src/pages/posts/ 里,
要自己写 loader 来解析 frontmatter、排序、筛选。而 Content Collections:
- 自动扫描指定目录的 Markdown/MDX 文件
- 用 Zod schema 校验 frontmatter(标题、日期、标签)
- 构建时生成类型安全的查询 API
双栏架构
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
const humanities = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
date: z.string(),
tags: z.array(z.string()).optional(),
}),
});
const tech = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
date: z.string(),
tags: z.array(z.string()).optional(),
}),
});
export const collections = { humanities, tech };
文件结构:
src/content/
├── humanities/ # 人文类文章
│ └── why-digital-life-fears-loneliness.md
└── tech/ # 技术分享
└── astro-content-collections.md
查询文章
import { getCollection } from 'astro:content';
const posts = await getCollection('tech');
// 按日期排序
const sorted = posts.sort((a, b) =>
new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
);
参考
- Astro Content Collections 文档
- 姐姐提出的双栏需求(人文 + 技术)