content-collections
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseContent Collections
Content Collections
Status: Production Ready ✅
Last Updated: 2025-11-07
Dependencies: None
Latest Versions: @content-collections/core@0.12.0, @content-collections/vite@0.2.7, zod@3.23.8
状态:生产就绪 ✅
最后更新:2025-11-07
依赖项:无
最新版本:@content-collections/core@0.12.0, @content-collections/vite@0.2.7, zod@3.23.8
What is Content Collections?
什么是 Content Collections?
Content Collections transforms local content files (Markdown/MDX) into type-safe TypeScript data with automatic validation at build time.
Problem it solves: Manual content parsing, lack of type safety, runtime errors from invalid frontmatter.
How it works:
- Define collections in (name, directory, Zod schema)
content-collections.ts - CLI/plugin scans filesystem, parses frontmatter, validates against schema
- Generates TypeScript modules in
.content-collections/generated/ - Import collections:
import { allPosts } from "content-collections"
Perfect for: Blogs, documentation sites, content-heavy apps with Cloudflare Workers, Vite, Next.js.
Content Collections 可将本地内容文件(Markdown/MDX)转换为类型安全的 TypeScript 数据,并在构建时自动进行验证。
解决的问题:手动解析内容、缺乏类型安全、无效前置元数据导致的运行时错误。
工作原理:
- 在中定义集合(名称、目录、Zod 架构)
content-collections.ts - CLI/插件扫描文件系统、解析前置元数据、根据架构验证内容
- 在目录生成 TypeScript 模块
.content-collections/generated/ - 导入集合:
import { allPosts } from "content-collections"
适用场景:博客、文档站点、基于 Cloudflare Workers、Vite、Next.js 的内容密集型应用。
Quick Start (5 Minutes)
快速开始(5分钟)
1. Install Dependencies
1. 安装依赖项
bash
undefinedbash
undefinedBun (recommended)
Bun(推荐)
bun add -d @content-collections/core @content-collections/vite zod
bun add -d @content-collections/core @content-collections/vite zod
npm
npm
npm install -D @content-collections/core @content-collections/vite zod
npm install -D @content-collections/core @content-collections/vite zod
pnpm
pnpm
pnpm add -D @content-collections/core @content-collections/vite zod
undefinedpnpm add -D @content-collections/core @content-collections/vite zod
undefined2. Configure TypeScript Path Alias
2. 配置 TypeScript 路径别名
Add to :
tsconfig.jsonjson
{
"compilerOptions": {
"paths": {
"content-collections": ["./.content-collections/generated"]
}
}
}- Configure Vite Plugin
Add to :
vite.config.tstypescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import contentCollections from "@content-collections/vite";
export default defineConfig({
plugins: [
react(),
contentCollections(), // MUST come after react()
],
});在中添加:
tsconfig.jsonjson
{
"compilerOptions": {
"paths": {
"content-collections": ["./.content-collections/generated"]
}
}
}4. Update .gitignore
3. 配置 Vite 插件
.content-collections/在中添加:
vite.config.tstypescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import contentCollections from "@content-collections/vite";
export default defineConfig({
plugins: [
react(),
contentCollections(), // 必须在 react() 之后
],
});5. Create Collection Config
4. 更新 .gitignore
Create in project root:
content-collections.tstypescript
import { defineCollection, defineConfig } from "@content-collections/core";
import { z } from "zod";
const posts = defineCollection({
name: "posts",
directory: "content/posts",
include: "*.md",
schema: z.object({
title: z.string(),
date: z.string(),
description: z.string(),
content: z.string(),
}),
});
export default defineConfig({
collections: [posts],
});.content-collections/6. Create Content Directory
5. 创建集合配置
bash
mkdir -p content/postsCreate :
content/posts/first-post.mdmarkdown
---
title: My First Post
date: 2025-11-07
description: Introduction to Content Collections
---在项目根目录创建:
content-collections.tstypescript
import { defineCollection, defineConfig } from "@content-collections/core";
import { z } from "zod";
const posts = defineCollection({
name: "posts",
directory: "content/posts",
include: "*.md",
schema: z.object({
title: z.string(),
date: z.string(),
description: z.string(),
content: z.string(),
}),
});
export default defineConfig({
collections: [posts],
});My First Post
6. 创建内容目录
Content goes here...
undefinedbash
mkdir -p content/posts创建:
content/posts/first-post.mdmarkdown
---
title: My First Post
date: 2025-11-07
description: Introduction to Content Collections
---7. Import and Use
My First Post
typescript
import { allPosts } from "content-collections";
console.log(allPosts); // Fully typed!Result: Type-safe content with autocomplete, validation, and HMR.
Content goes here...
undefinedCritical Rules
7. 导入并使用
✅ Always Do:
—
- Add path alias to tsconfig.json - Required for imports to work
- Add .content-collections to .gitignore - Generated files shouldn't be committed
- Use Standard Schema validators - Zod, Valibot, ArkType supported
- Include field in schema - Required for frontmatter parsing
content - Await compileMDX in transforms - MDX compilation is async
- Put contentCollections() after react() in Vite - Plugin order matters
typescript
import { allPosts } from "content-collections";
console.log(allPosts); // 完全支持类型提示!结果:具备自动补全、验证和热模块替换(HMR)的类型安全内容。
❌ Never Do:
关键规则
—
✅ 必须遵守:
- Commit .content-collections directory - Always generated, never committed
- Use non-standard validators - Must support StandardSchema spec
- Forget to restart dev server after config changes - Required for new collections
- Use sync transforms with async operations - Transform must be async
- Double-wrap path alias - Use not
content-collections./content-collections - Import from wrong package - for config,
@content-collections/corefor datacontent-collections
- 在 tsconfig.json 中添加路径别名 - 是导入功能正常工作的必要条件
- 将 .content-collections 添加到 .gitignore - 生成的文件不应提交到版本库
- 使用标准架构验证器 - 支持 Zod、Valibot、ArkType
- 在架构中包含字段 - 是解析前置元数据的必要条件
content - 在转换中等待 compileMDX - MDX 编译是异步操作
- 在 Vite 中将 contentCollections() 放在 react() 之后 - 插件顺序很重要
Known Issues Prevention
❌ 切勿执行:
Issue #1: Module not found: 'content-collections'
—
Error:
Cannot find module 'content-collections' or its corresponding type declarationsWhy it happens: Missing TypeScript path alias configuration.
Prevention:
Add to :
tsconfig.jsonjson
{
"compilerOptions": {
"paths": {
"content-collections": ["./.content-collections/generated"]
}
}
}Restart TypeScript server in VS Code: → "TypeScript: Restart TS Server"
Cmd+Shift+PSource: Common user error
- 提交 .content-collections 目录 - 该目录始终是生成的,绝不提交
- 使用非标准验证器 - 必须符合 StandardSchema 规范
- 修改配置后忘记重启开发服务器 - 新增集合需要重启服务器
- 在同步转换中使用异步操作 - 转换函数必须是异步的
- 重复包裹路径别名 - 使用而非
content-collections./content-collections - 从错误的包导入 - 配置使用,数据导入使用
@content-collections/corecontent-collections
Issue #2: Vite Constant Restart Loop
已知问题预防
—
问题 #1:找不到模块:'content-collections'
Error: Dev server continuously restarts, infinite loop.
Why it happens: Vite watching directory changes, which triggers regeneration.
.content-collectionsPrevention:
- Add to :
.gitignore
.content-collections/- Add to (if still happening):
vite.config.ts
typescript
export default defineConfig({
server: {
watch: {
ignored: ["**/.content-collections/**"],
},
},
});Source: GitHub Issue #591 (TanStack Start)
错误信息:
Cannot find module 'content-collections' or its corresponding type declarations原因:缺少 TypeScript 路径别名配置。
解决方法:
在中添加:
tsconfig.jsonjson
{
"compilerOptions": {
"paths": {
"content-collections": ["./.content-collections/generated"]
}
}
}在 VS Code 中重启 TypeScript 服务器: → "TypeScript: Restart TS Server"
Cmd+Shift+P来源:常见用户错误
Issue #3: Transform Types Not Reflected
问题 #2:Vite 持续重启循环
Error: TypeScript types don't match transformed documents.
Why it happens: TypeScript doesn't automatically infer transform function return type.
Prevention:
Explicitly type your transform return:
typescript
const posts = defineCollection({
name: "posts",
// ... schema
transform: (post): PostWithSlug => ({ // Type the return!
...post,
slug: post._meta.path.replace(/\.md$/, ""),
}),
});
type PostWithSlug = {
// ... schema fields
slug: string;
};Source: GitHub Issue #396
错误信息:开发服务器持续重启,进入无限循环。
原因:Vite 监听目录的变化,触发重新生成操作。
.content-collections解决方法:
- 在中添加:
.gitignore
.content-collections/- 如果问题仍然存在,在中添加:
vite.config.ts
typescript
export default defineConfig({
server: {
watch: {
ignored: ["**/.content-collections/**"],
},
},
});来源:GitHub Issue #591 (TanStack Start)
Issues #4-8: Advanced Troubleshooting
问题 #3:转换类型未同步更新
Additional issues covered in :
references/advanced-troubleshooting.md| Issue | Error | Quick Fix |
|---|---|---|
| #4 | Collection not updating | Verify glob pattern, restart dev server |
| #5 | MDX/Shiki errors | Use compatible versions (shiki ^1.0.0) |
| #6 | MDX path aliases fail | Use relative paths in MDX imports |
| #7 | Unclear validation errors | Add custom Zod error messages |
| #8 | Ctrl+C doesn't stop | Use |
错误信息:TypeScript 类型与转换后的文档不匹配。
原因:TypeScript 无法自动推断转换函数的返回类型。
解决方法:
显式指定转换函数的返回类型:
typescript
const posts = defineCollection({
name: "posts",
// ... 架构配置
transform: (post): PostWithSlug => ({ // 指定返回类型!
...post,
slug: post._meta.path.replace(/\.md$/, ""),
}),
});
type PostWithSlug = {
// ... 架构字段
slug: string;
};来源:GitHub Issue #396
Configuration Patterns
问题 #4-8:高级故障排除
| Pattern | Use Case | Template |
|---|---|---|
| Basic Blog | Single collection, Markdown only | |
| Multi-Collection | Posts + Docs, nested folders | |
| Transform Functions | Computed fields (slug, readingTime) | See |
| MDX + React | Syntax highlighting, React components | |
For detailed schema patterns (dates, tags, validation), load .
references/schema-patterns.md更多问题请查看:
references/advanced-troubleshooting.md| 问题 | 错误信息 | 快速修复 |
|---|---|---|
| #4 | 集合未更新 | 验证 glob 模式,重启开发服务器 |
| #5 | MDX/Shiki 错误 | 使用兼容版本(shiki ^1.0.0) |
| #6 | MDX 路径别名失效 | 在 MDX 导入中使用相对路径 |
| #7 | 验证错误信息不清晰 | 添加自定义 Zod 错误提示 |
| #8 | Ctrl+C 无法终止进程 | 使用 |
React Component Integration
配置模式
Using Collections in React
—
tsx
import { allPosts } from "content-collections";
export function BlogList() {
return (
<ul>
{allPosts.map((post) => (
<li key={post._meta.path}>
<h2>{post.title}</h2>
<p>{post.description}</p>
<time>{post.date}</time>
</li>
))}
</ul>
);
}| 模式 | 适用场景 | 模板 |
|---|---|---|
| 基础博客 | 单一集合,仅支持 Markdown | |
| 多集合 | 文章 + 文档,嵌套文件夹 | |
| 转换函数 | 计算字段(slug、阅读时长) | 查看 |
| MDX + React | 语法高亮、React 组件 | |
如需了解详细的架构模式(日期、标签、验证),请查看。
references/schema-patterns.mdRendering MDX Content
React 组件集成
—
在 React 中使用集合
tsx
import { MDXContent } from "@content-collections/mdx/react";
export function BlogPost({ post }: { post: { mdx: string } }) {
return (
<article>
<MDXContent code={post.mdx} />
</article>
);
}tsx
import { allPosts } from "content-collections";
export function BlogList() {
return (
<ul>
{allPosts.map((post) => (
<li key={post._meta.path}>
<h2>{post.title}</h2>
<p>{post.description}</p>
<time>{post.date}</time>
</li>
))}
</ul>
);
}Cloudflare Workers Deployment
渲染 MDX 内容
Content Collections is perfect for Cloudflare Workers (build-time only, no runtime filesystem). Use template for config.
templates/wrangler.tomlPattern: → (Vite plugin handles content-collections automatically)
vite buildwrangler deployFor detailed deployment guide, load .
references/deployment-guide.mdtsx
import { MDXContent } from "@content-collections/mdx/react";
export function BlogPost({ post }: { post: { mdx: string } }) {
return (
<article>
<MDXContent code={post.mdx} />
</article>
);
}Bundled Resources
Cloudflare Workers 部署
Templates (9 copy-paste files)
—
content-collections.tscontent-collections-multi.tscontent-collections-mdx.tstsconfig.jsonvite.config.tsBlogList.tsxBlogPost.tsxblog-post.mdwrangler.tomlContent Collections 非常适合 Cloudflare Workers(仅在构建时运行,无需运行时文件系统)。使用模板进行配置。
templates/wrangler.toml模式: → (Vite 插件会自动处理 content-collections)
vite buildwrangler deploy如需详细部署指南,请查看。
references/deployment-guide.mdScripts
捆绑资源
—
模板(9个可直接复制的文件)
init-content-collections.shcontent-collections.tscontent-collections-multi.tscontent-collections-mdx.tstsconfig.jsonvite.config.tsBlogList.tsxBlogPost.tsxblog-post.mdwrangler.tomlDependencies
脚本
Required
—
json
{
"devDependencies": {
"@content-collections/core": "^0.12.0",
"@content-collections/vite": "^0.2.7",
"zod": "^3.23.8"
}
}init-content-collections.shOptional (MDX)
依赖项
—
必填
json
{
"devDependencies": {
"@content-collections/markdown": "^0.1.4",
"@content-collections/mdx": "^0.2.2",
"shiki": "^1.0.0"
}
}json
{
"devDependencies": {
"@content-collections/core": "^0.12.0",
"@content-collections/vite": "^0.2.7",
"zod": "^3.23.8"
}
}Official Documentation
可选(MDX 支持)
- Official Site: https://www.content-collections.dev
- Documentation: https://www.content-collections.dev/docs
- GitHub: https://github.com/sdorra/content-collections
- Vite Plugin: https://www.content-collections.dev/docs/vite
- MDX Integration: https://www.content-collections.dev/docs/mdx
json
{
"devDependencies": {
"@content-collections/markdown": "^0.1.4",
"@content-collections/mdx": "^0.2.2",
"shiki": "^1.0.0"
}
}Package Versions (Verified 2025-11-07)
官方文档
| Package | Version | Status |
|---|---|---|
| @content-collections/core | 0.12.0 | ✅ Latest stable |
| @content-collections/vite | 0.2.7 | ✅ Latest stable |
| @content-collections/mdx | 0.2.2 | ✅ Latest stable |
| @content-collections/markdown | 0.1.4 | ✅ Latest stable |
| zod | 3.23.8 | ✅ Latest stable |
Quick Troubleshooting
包版本(2025-11-07 验证)
| Problem | Solution |
|---|---|
| TypeScript can't find module | Add path alias to |
| Vite keeps restarting | Add |
| Changes not reflecting | Restart dev server, verify glob pattern |
| MDX compilation errors | Check Shiki version compatibility |
| Validation errors unclear | Add custom Zod error messages |
| 包 | 版本 | 状态 |
|---|---|---|
| @content-collections/core | 0.12.0 | ✅ 最新稳定版 |
| @content-collections/vite | 0.2.7 | ✅ 最新稳定版 |
| @content-collections/mdx | 0.2.2 | ✅ 最新稳定版 |
| @content-collections/markdown | 0.1.4 | ✅ 最新稳定版 |
| zod | 3.23.8 | ✅ 最新稳定版 |
When to Load References
快速故障排除
| Reference | Load When... |
|---|---|
| Setting up complex schemas, date validation, optional fields |
| Adding computed fields, async transforms, slugs |
| Integrating React components in MDX, syntax highlighting |
| Deploying to Cloudflare Workers or other platforms |
| Issues #4-8 (file watching, path aliases, process hanging) |
| 问题 | 解决方案 |
|---|---|
| TypeScript 找不到模块 | 在 |
| Vite 持续重启 | 将 |
| 修改内容未同步 | 重启开发服务器,验证 glob 模式 |
| MDX 编译错误 | 检查 Shiki 版本兼容性 |
| 验证错误信息不清晰 | 添加自定义 Zod 错误提示 |
Complete Setup Checklist
何时查看参考文档
- Installed and
@content-collections/core@content-collections/vite - Installed for schema validation
zod - Added path alias to
tsconfig.json - Added to
contentCollections()(after react())vite.config.ts - Added to
.content-collections/.gitignore - Created in project root
content-collections.ts - Created content directory (e.g., )
content/posts/ - Defined collection with Zod schema
- Created first content file with frontmatter
- Imported collection in React component
- Verified types work (autocomplete)
- Tested hot reloading (change content file)
| 参考文档 | 查看时机... |
|---|---|
| 设置复杂架构、日期验证、可选字段时 |
| 添加计算字段、异步转换、slug 时 |
| 在 MDX 中集成 React 组件、实现语法高亮时 |
| 部署到 Cloudflare Workers 或其他平台时 |
| 遇到问题 #4-8(文件监听、路径别名、进程挂起)时 |
—
完整安装检查清单
—
- 已安装和
@content-collections/core@content-collections/vite - 已安装用于架构验证
zod - 已在中添加路径别名
tsconfig.json - 已在中添加
vite.config.ts(在 react() 之后)contentCollections() - 已将添加到
.content-collections/.gitignore - 已在项目根目录创建
content-collections.ts - 已创建内容目录(例如:)
content/posts/ - 已使用 Zod 架构定义集合
- 已创建包含前置元数据的首个内容文件
- 已在 React 组件中导入集合
- 已验证类型功能正常(自动补全)
- 已测试热重载(修改内容文件)