Astro 内容集合速记

#技术#Astro

搭这个站用到的 Astro 内容集合(Content Collections)核心就三步。

1. 定义集合

src/content.config.ts 里用 glob loader 指向 markdown 目录:

const posts = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
  schema: z.object({ title: z.string(), pubDate: z.coerce.date() }),
});

schema 用 zod,frontmatter 缺字段或类型错会在构建时报错——这点很省心。

2. 列出文章

const posts = await getCollection('posts');

排序就普通 sort,按 pubDate 倒序。

3. 渲染单篇

const { Content } = await render(post);
---
<Content />

getStaticPathsparams: { slug: post.id } 自动给每篇生成 /posts/<id>/ 页面。


没有数据库,没有后端,markdown 文件就是数据源。简单到不会坏。

评论