用途:把本地 Markdown/MDX 内容转换成类型安全的 TypeScript 数据,并在构建时用校验模式自动验证,解决手动解析内容、缺少类型安全、frontmatter 无效导致的运行时错误。
主要能力:在 content-collections.ts 中用 defineCollection 定义集合(name、directory、include、schema,schema 用 Zod 等 Standard Schema 校验器);CLI/Vite 插件扫描文件、解析 frontmatter、按 schema 校验,并在 .content-collections/generated/ 生成 TS 模块;通过 import { allPosts } from "content-collections" 使用,支持自动补全、校验与 HMR。MDX 可选集成 @content-collections/mdx,用 MDXContent 渲染。
使用方式:安装 @content-collections/core、@content-collections/vite、zod(如 bun add -d @content-collections/core @content-collections/vite zod);在 tsconfig.json 添加路径别名 "content-collections": ["./.content-collections/generated"];在 vite.config.ts 中把 contentCollections() 放在 react() 之后;.gitignore 添加 .content-collections/;根目录创建 content-collections.ts 与内容目录。可搭配 Cloudflare Workers:vite build 后 wrangler deploy。
适用场景:博客、文档站、内容密集应用,以及与 Vite、React、Next.js、Cloudflare Workers 的构建时内容处理。
限制与注意:必须配置 tsconfig 路径别名,.content-collections 目录不要提交;schema 需包含 content 字段;MDX 编译需 await;修改配置后需重启开发服务器;transform 返回类型需显式标注;插件顺序、路径别名、Shiki 与 MDX 版本兼容等可能引发问题;日期、tags 等复杂 schema 与部署细节可参考官方文档与仓库。官方站点:https://www.content-collections.dev,文档:https://www.content-collections.dev/docs,GitHub:https://github.com/sdorra/content-collections。