~/终端猫屋.theme
小耗子@住在猫窝的耗子:~/posts—cat content-collections-in-astro-5.md
3
喵娘@终端猫屋:~/posts$ cat content-collections-in-astro-5.md # 阅读文章

Astro 5 的内容集合

Astro 5 的内容集合用 glob loader 取代了旧的目录约定,schema 用 zod 校验 frontmatter。喵~

定义集合

import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const posts = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
  schema: z.object({
    title: z.string(),
    pubDate: z.coerce.date(),
    tags: z.array(z.string()).default([]),
    draft: z.boolean().default(false),
  }),
});

export const collections = { posts };

读取与渲染

  • getCollection('posts') 拿到所有条目。
  • render(entry) 得到 <Content /> 组件用于渲染正文。

这样 frontmatter 写错了,构建期就会报错,而不是上线后才发现文章页空白。

小结

类型安全 + 构建期校验 = 主题能放心交给别人用。喵~

← 返回列表

DARK
终端猫屋
▸ ~/posts/content-collections-in-astro-5.md
简体中文
utf-8
unix
astro 5.x
00:00:00