视频加载失败

Astro 内容管线速记:Content Collections 从入门到顺手

269 字
1 分钟
Astro 内容管线速记:Content Collections 从入门到顺手

把博客搬到 Astro 之后,最让我安心的是内容管线:Markdown 不再是「随便放的文件」,而是有类型约束的数据源。

从 glob 到 getCollection#

以前常见的写法是拿 import.meta.glob 扫目录,再自己解析 frontmatter——校验全靠自觉。Content Collections 的思路是先声明 schema:

src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const blog = defineCollection({
loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
schema: z.object({
title: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
}),
});
export const collections = { blog };

少写一个必填字段,构建期直接报错,而不是上线后渲染出空白标题。这件事对懒人特别友好:schema 就是文档。

路由即数据#

文章页用 getStaticPaths 展开集合,参数就是 slug,构建完每个 URL 都是一张静态 HTML:

dist/posts/hello-again-warm-editorial/index.html
npx astro build
# dist/rss.xml

常用字段约定如下:

字段类型必填
titlestring
pubDatedate
tagsstring[]可选

小结#

数据有 schema、路由静态展开、代码高亮交给 Shiki 在构建期做完——内容站的复杂度被框架吃掉了,剩下的时间可以专心写字。

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
Astro 内容管线速记:Content Collections 从入门到顺手
https://ryuki.icu/posts/astro-content-pipeline-notes/
作者
RK
发布于
2025-10-18
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
RK
朝花夕拾,写字为了想清楚。
公告
朝花夕拾——早晨的花,傍晚再拾起来。
分类
标签
最新动态
站点统计
文章
6
分类
3
标签
6
总字数
1,992
运行时长
0
最后活动
0 天前
站点信息
构建平台
Cloudflare Pages
博客版本
Firefly v6.16.4
文章许可
CC BY-NC-SA 4.0