用途:在 Astro 中搭建和配置内容集合,用类型安全 schema 管理结构化内容,适合新建博客、文档、作品集,或从 Astro.glob() 迁移。
结构与定义:内容放在 src/content/,config.ts 中定义 schema;集合可为 content(Markdown/MDX)或 data(JSON/YAML),支持子目录。使用 defineCollection 与 z 定义字段,可设默认值和可选字段。
常见模式:用 image() 校验图片,用 reference('authors') 引用其他集合,用 z.enum() 限定分类或状态。
查询与渲染:用 getCollection 获取全部或按条件过滤,用 getEntry 取单条;调用 post.render() 得到 Content 与 headings,再渲染。
动态路由:在 src/pages/blog/[...slug].astro 中用 getStaticPaths 返回 params 与 props。
生成类型:运行 npx astro sync 或 astro dev 生成 TypeScript 类型。
迁移与排错:从 Astro.glob() 迁移时,把文件移入 src/content/blog/,创建 config.ts,将 Astro.glob() 换成 getCollection(),并改用 getStaticPaths();出现 schema 错误可重新运行 astro sync,集合未找到需确认目录直接在 src/content/ 下,类型错误需确保 config.ts 导出 collections,图片校验失败改用 schema: ({ image }) => 函数写法。
限制:资料未提供定价、平台支持范围或其他未述细节。