这篇是本站第一篇教程,也是建站过程中的实际操作记录。
为什么要用内容集合
Markdown 文件夹谁都会放,但如果没有约束,三个月后你会写出五种不同写法的日期、两种拼法的标签,然后首页列表按日期排序时就悄悄错位了。
内容集合的价值是把约定写进代码:字段缺失、类型写错、日期格式不对,构建阶段就报错,而不是上线后才发现某篇文章从列表里消失了。
定义集合
import { defineCollection, z } from "astro:content";
import { glob } from "astro/loaders";
const study = defineCollection({
loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/content/study" }),
schema: z.object({
title: z.string(),
date: z.coerce.date(),
category: z.enum(["notes", "tutorials", "projects", "resources"]),
summary: z.string(),
tags: z.array(z.string()).default([]),
minutes: z.number().default(6),
draft: z.boolean().default(false),
}),
});
export const collections = { study };
几个细节值得记下来:
z.coerce.date()允许 frontmatter 里直接写2026-11-12,解析成 Date 对象;z.enum把这四个分类钉死,写错分类会直接构建失败;default让可选字段有兜底,写作时不用每次都填。
取数据
---
import { getCollection } from "astro:content";
const posts = (await getCollection("study", ({ data }) => !data.draft))
.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
---
draft: true 的文章在本地可见、不进入列表,这个开关在写作时很有用。
评论