content-collections

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Content 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:
  1. Define collections in
    content-collections.ts
    (name, directory, Zod schema)
  2. CLI/plugin scans filesystem, parses frontmatter, validates against schema
  3. Generates TypeScript modules in
    .content-collections/generated/
  4. 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 数据,并在构建时自动进行验证。
解决的问题:手动解析内容、缺乏类型安全、无效前置元数据导致的运行时错误。
工作原理
  1. content-collections.ts
    中定义集合(名称、目录、Zod 架构)
  2. CLI/插件扫描文件系统、解析前置元数据、根据架构验证内容
  3. .content-collections/generated/
    目录生成 TypeScript 模块
  4. 导入集合:
    import { allPosts } from "content-collections"
适用场景:博客、文档站点、基于 Cloudflare Workers、Vite、Next.js 的内容密集型应用。

Quick Start (5 Minutes)

快速开始(5分钟)

1. Install Dependencies

1. 安装依赖项

bash
undefined
bash
undefined

Bun (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
undefined
pnpm add -D @content-collections/core @content-collections/vite zod
undefined

2. Configure TypeScript Path Alias

2. 配置 TypeScript 路径别名

Add to
tsconfig.json
:
json
{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}

  1. Configure Vite Plugin
Add to
vite.config.ts
:
typescript
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.json
中添加:
json
{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}

4. Update .gitignore

3. 配置 Vite 插件

.content-collections/
vite.config.ts
中添加:
typescript
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
content-collections.ts
in project root:
typescript
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/posts
Create
content/posts/first-post.md
:
markdown
---
title: My First Post
date: 2025-11-07
description: Introduction to Content Collections
---
在项目根目录创建
content-collections.ts
typescript
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...
undefined
bash
mkdir -p content/posts
创建
content/posts/first-post.md
markdown
---
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...
undefined

Critical Rules

7. 导入并使用

✅ Always Do:

  1. Add path alias to tsconfig.json - Required for imports to work
  2. Add .content-collections to .gitignore - Generated files shouldn't be committed
  3. Use Standard Schema validators - Zod, Valibot, ArkType supported
  4. Include
    content
    field in schema
    - Required for frontmatter parsing
  5. Await compileMDX in transforms - MDX compilation is async
  6. Put contentCollections() after react() in Vite - Plugin order matters
typescript
import { allPosts } from "content-collections";

console.log(allPosts); // 完全支持类型提示!
结果:具备自动补全、验证和热模块替换(HMR)的类型安全内容。

❌ Never Do:

关键规则

✅ 必须遵守:

  1. Commit .content-collections directory - Always generated, never committed
  2. Use non-standard validators - Must support StandardSchema spec
  3. Forget to restart dev server after config changes - Required for new collections
  4. Use sync transforms with async operations - Transform must be async
  5. Double-wrap path alias - Use
    content-collections
    not
    ./content-collections
  6. Import from wrong package -
    @content-collections/core
    for config,
    content-collections
    for data

  1. 在 tsconfig.json 中添加路径别名 - 是导入功能正常工作的必要条件
  2. 将 .content-collections 添加到 .gitignore - 生成的文件不应提交到版本库
  3. 使用标准架构验证器 - 支持 Zod、Valibot、ArkType
  4. 在架构中包含
    content
    字段
    - 是解析前置元数据的必要条件
  5. 在转换中等待 compileMDX - MDX 编译是异步操作
  6. 在 Vite 中将 contentCollections() 放在 react() 之后 - 插件顺序很重要

Known Issues Prevention

❌ 切勿执行:

Issue #1: Module not found: 'content-collections'

Error:
Cannot find module 'content-collections' or its corresponding type declarations
Why it happens: Missing TypeScript path alias configuration.
Prevention:
Add to
tsconfig.json
:
json
{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}
Restart TypeScript server in VS Code:
Cmd+Shift+P
→ "TypeScript: Restart TS Server"
Source: Common user error

  1. 提交 .content-collections 目录 - 该目录始终是生成的,绝不提交
  2. 使用非标准验证器 - 必须符合 StandardSchema 规范
  3. 修改配置后忘记重启开发服务器 - 新增集合需要重启服务器
  4. 在同步转换中使用异步操作 - 转换函数必须是异步的
  5. 重复包裹路径别名 - 使用
    content-collections
    而非
    ./content-collections
  6. 从错误的包导入 - 配置使用
    @content-collections/core
    ,数据导入使用
    content-collections

Issue #2: Vite Constant Restart Loop

已知问题预防

问题 #1:找不到模块:'content-collections'

Error: Dev server continuously restarts, infinite loop.
Why it happens: Vite watching
.content-collections
directory changes, which triggers regeneration.
Prevention:
  1. Add to
    .gitignore
    :
.content-collections/
  1. Add to
    vite.config.ts
    (if still happening):
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.json
中添加:
json
{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}
在 VS Code 中重启 TypeScript 服务器:
Cmd+Shift+P
→ "TypeScript: Restart TS Server"
来源:常见用户错误

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
目录的变化,触发重新生成操作。
解决方法
  1. .gitignore
    中添加:
.content-collections/
  1. 如果问题仍然存在,在
    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
:
IssueErrorQuick Fix
#4Collection not updatingVerify glob pattern, restart dev server
#5MDX/Shiki errorsUse compatible versions (shiki ^1.0.0)
#6MDX path aliases failUse relative paths in MDX imports
#7Unclear validation errorsAdd custom Zod error messages
#8Ctrl+C doesn't stopUse
kill -9
or separate watch command

错误信息: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:高级故障排除

PatternUse CaseTemplate
Basic BlogSingle collection, Markdown only
templates/content-collections.ts
Multi-CollectionPosts + Docs, nested folders
templates/content-collections-multi.ts
Transform FunctionsComputed fields (slug, readingTime)See
references/transform-cookbook.md
MDX + ReactSyntax highlighting, React components
templates/content-collections-mdx.ts
For detailed schema patterns (dates, tags, validation), load
references/schema-patterns.md
.

更多问题请查看
references/advanced-troubleshooting.md
问题错误信息快速修复
#4集合未更新验证 glob 模式,重启开发服务器
#5MDX/Shiki 错误使用兼容版本(shiki ^1.0.0)
#6MDX 路径别名失效在 MDX 导入中使用相对路径
#7验证错误信息不清晰添加自定义 Zod 错误提示
#8Ctrl+C 无法终止进程使用
kill -9
或单独的监听命令

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
templates/content-collections.ts
多集合文章 + 文档,嵌套文件夹
templates/content-collections-multi.ts
转换函数计算字段(slug、阅读时长)查看
references/transform-cookbook.md
MDX + React语法高亮、React 组件
templates/content-collections-mdx.ts
如需了解详细的架构模式(日期、标签、验证),请查看
references/schema-patterns.md

Rendering 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
templates/wrangler.toml
for config.
Pattern:
vite build
wrangler deploy
(Vite plugin handles content-collections automatically)
For detailed deployment guide, load
references/deployment-guide.md
.

tsx
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.ts
,
content-collections-multi.ts
,
content-collections-mdx.ts
,
tsconfig.json
,
vite.config.ts
,
BlogList.tsx
,
BlogPost.tsx
,
blog-post.md
,
wrangler.toml
Content Collections 非常适合 Cloudflare Workers(仅在构建时运行,无需运行时文件系统)。使用模板
templates/wrangler.toml
进行配置。
模式
vite build
wrangler deploy
(Vite 插件会自动处理 content-collections)
如需详细部署指南,请查看
references/deployment-guide.md

Scripts

捆绑资源

模板(9个可直接复制的文件)

init-content-collections.sh
- One-command automated setup

content-collections.ts
,
content-collections-multi.ts
,
content-collections-mdx.ts
,
tsconfig.json
,
vite.config.ts
,
BlogList.tsx
,
BlogPost.tsx
,
blog-post.md
,
wrangler.toml

Dependencies

脚本

Required

json
{
  "devDependencies": {
    "@content-collections/core": "^0.12.0",
    "@content-collections/vite": "^0.2.7",
    "zod": "^3.23.8"
  }
}
init-content-collections.sh
- 一键自动化安装脚本

Optional (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 支持)

json
{
  "devDependencies": {
    "@content-collections/markdown": "^0.1.4",
    "@content-collections/mdx": "^0.2.2",
    "shiki": "^1.0.0"
  }
}

Package Versions (Verified 2025-11-07)

官方文档

PackageVersionStatus
@content-collections/core0.12.0✅ Latest stable
@content-collections/vite0.2.7✅ Latest stable
@content-collections/mdx0.2.2✅ Latest stable
@content-collections/markdown0.1.4✅ Latest stable
zod3.23.8✅ Latest stable

Quick Troubleshooting

包版本(2025-11-07 验证)

ProblemSolution
TypeScript can't find moduleAdd path alias to
tsconfig.json
, restart TS server
Vite keeps restartingAdd
.content-collections/
to
.gitignore
Changes not reflectingRestart dev server, verify glob pattern
MDX compilation errorsCheck Shiki version compatibility
Validation errors unclearAdd custom Zod error messages

版本状态
@content-collections/core0.12.0✅ 最新稳定版
@content-collections/vite0.2.7✅ 最新稳定版
@content-collections/mdx0.2.2✅ 最新稳定版
@content-collections/markdown0.1.4✅ 最新稳定版
zod3.23.8✅ 最新稳定版

When to Load References

快速故障排除

ReferenceLoad When...
schema-patterns.md
Setting up complex schemas, date validation, optional fields
transform-cookbook.md
Adding computed fields, async transforms, slugs
mdx-components.md
Integrating React components in MDX, syntax highlighting
deployment-guide.md
Deploying to Cloudflare Workers or other platforms
advanced-troubleshooting.md
Issues #4-8 (file watching, path aliases, process hanging)

问题解决方案
TypeScript 找不到模块
tsconfig.json
中添加路径别名,重启 TS 服务器
Vite 持续重启
.content-collections/
添加到
.gitignore
修改内容未同步重启开发服务器,验证 glob 模式
MDX 编译错误检查 Shiki 版本兼容性
验证错误信息不清晰添加自定义 Zod 错误提示

Complete Setup Checklist

何时查看参考文档

  • Installed
    @content-collections/core
    and
    @content-collections/vite
  • Installed
    zod
    for schema validation
  • Added path alias to
    tsconfig.json
  • Added
    contentCollections()
    to
    vite.config.ts
    (after react())
  • Added
    .content-collections/
    to
    .gitignore
  • Created
    content-collections.ts
    in project root
  • 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)
参考文档查看时机...
schema-patterns.md
设置复杂架构、日期验证、可选字段时
transform-cookbook.md
添加计算字段、异步转换、slug 时
mdx-components.md
在 MDX 中集成 React 组件、实现语法高亮时
deployment-guide.md
部署到 Cloudflare Workers 或其他平台时
advanced-troubleshooting.md
遇到问题 #4-8(文件监听、路径别名、进程挂起)时

完整安装检查清单

  • 已安装
    @content-collections/core
    @content-collections/vite
  • 已安装
    zod
    用于架构验证
  • 已在
    tsconfig.json
    中添加路径别名
  • 已在
    vite.config.ts
    中添加
    contentCollections()
    (在 react() 之后)
  • 已将
    .content-collections/
    添加到
    .gitignore
  • 已在项目根目录创建
    content-collections.ts
  • 已创建内容目录(例如:
    content/posts/
  • 已使用 Zod 架构定义集合
  • 已创建包含前置元数据的首个内容文件
  • 已在 React 组件中导入集合
  • 已验证类型功能正常(自动补全)
  • 已测试热重载(修改内容文件)