Content Collections 是一个 TypeScript 优先的构建工具,用于把本地 Markdown/MDX 内容文件转换为类型安全的 TypeScript 数据,并在构建时进行自动校验。它主要解决手动解析内容、缺乏类型安全、无效 frontmatter 导致运行时错误等问题。其工作方式为:在 content-collections.ts 中定义集合(名称、目录、Zod schema),CLI 或插件扫描文件系统、解析 frontmatter 并按 schema 校验,随后在 .content-collections/generated/ 生成 TypeScript 模块,通过 import { allPosts } from "content-collections" 使用,适合博客、文档站点及配合 Vite、Next.js、Cloudflare Workers 的内容型应用。
快速上手:安装 pnpm add -D @content-collections/core @content-collections/vite zod;在 tsconfig.json 添加路径别名 "content-collections": ["./.content-collections/generated"];在 vite.config.ts 中引入并调用 contentCollections()(须放在 react() 之后);将 .content-collections/ 加入 .gitignore;在项目根创建 content-collections.ts 定义集合;创建内容目录与带 frontmatter 的 Markdown 文件;最后在组件中导入集合使用。
主要能力包括:基于 Zod、Valibot、ArkType 等 Standard Schema 校验器的 schema 校验;通过 transform 函数计算额外字段(如 slug、阅读时长);MDX 编译与语法高亮、React 组件渲染;多集合配置;基于 Vite 的热更新。限制与注意事项:勿提交 .content-collections 目录;schema 中需包含 content 字段;MDX 编译需 await;配置变更后需重启开发服务器;MDX 导入不支持 tsconfig 路径别名,需用相对路径。已知问题包括模块找不到(缺路径别名)、Vite 反复重启(需忽略 .content-collections)、transform 类型未反映(需显式标注返回类型)、Shiki 版本兼容、Ctrl+C 无法退出等。官方文档见 https://www.content-collections.dev/docs。