Astro 内容集合入门笔记
Astro前端学习笔记
什么是内容集合
内容集合(Content Collections)是 Astro 管理 Markdown 等内容的官方方式。它在 src/content.config.ts 中定义,通过加载器把文件读进来,并用 Zod schema 校验 frontmatter。
定义一个博客集合
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const blog = defineCollection({
loader: glob({ base: './src/content/blog', pattern: '**/*.md' }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
export const collections = { blog };
在页面中使用
列表页用 getCollection 取全部文章并排序:
---
import { getCollection } from 'astro:content';
const posts = await getCollection('blog');
---
详情页则配合动态路由和 render 函数渲染正文:
---
import { render } from 'astro:content';
const { Content } = await render(post);
---
<Content />
小结
内容集合把「内容」和「展示」干净地分开了:写文章只需要关注 Markdown 本身,类型安全由 schema 兜底。对于个人博客来说,这是目前最省心的方案之一。