mcpField
C
content-collections

content-collections

github.com/secondsky开发240128 次安装5 周前更新
代码仓库

关于 content-collections

Content Collections 将本地 Markdown/MDX 文件转为带类型的 TypeScript 数据,并在构建时按模式验证。适用于博客、文档站点及内容型应用。

主要功能

  1. 01扫描文件并解析 frontmatter
  2. 02使用 Zod 等模式验证内容
  3. 03生成带类型的 TypeScript 模块
  4. 04支持 Markdown 与 MDX 工作流
  5. 05提供 Vite 插件及热更新

适用场景

  1. 01构建博客文章集合并在应用中导入
  2. 02为文档站点验证本地内容
  3. 03将 MDX 内容接入 React 组件
  4. 04在 Vite 项目中生成类型安全内容

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill content-collections

安装后在 Claude Code 中输入/content-collections确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
example-template.txt
references/
advanced-troubleshooting.md
deployment-guide.md
mdx-components.md
schema-patterns.md
transform-cookbook.md
scripts/
example-script.sh
init-content-collections.sh
templates/
blog-post.md
BlogList.tsx
BlogPost.tsx
content-collections-mdx.ts
content-collections-multi.ts
content-collections.ts
tsconfig.json
vite.config.ts
wrangler.toml

详细介绍

Content Collections

状态:生产就绪 ✅ 上次更新:2025-11-07 依赖项:无 最新版本:@content-collections/[email protected]、@content-collections/[email protected]、[email protected]


什么是 Content Collections?

Content Collections 会将本地内容文件(Markdown/MDX)转换为类型安全的 TypeScript 数据,并在构建时自动验证。

解决的问题:手动解析内容、缺乏类型安全,以及无效 frontmatter 导致的运行时错误。

工作原理:

  1. 在 content-collections.ts 中定义集合(名称、目录、Zod 模式)
  2. CLI/插件扫描文件系统、解析 frontmatter,并根据模式进行验证
  3. 在 .content-collections/generated/ 中生成 TypeScript 模块
  4. 导入集合:import { allPosts } from "content-collections"

适用场景:博客、文档站点,以及使用 Cloudflare Workers、Vite、Next.js 的内容密集型应用。


快速入门(5 分钟)

1. 安装依赖项
# Bun (recommended)
bun add -d @content-collections/core @content-collections/vite zod

# npm
npm install -D @content-collections/core @content-collections/vite zod

# pnpm
pnpm add -D @content-collections/core @content-collections/vite zod
2. 配置 TypeScript 路径别名

添加到 tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}
  1. 配置 Vite 插件

添加到 vite.config.ts:

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()
  ],
});
4. 更新 .gitignore
.content-collections/
5. 创建集合配置

在项目根目录创建 content-collections.ts:

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],
});
6. 创建内容目录
mkdir -p content/posts

创建 content/posts/first-post.md:

---
title: My First Post
date: 2025-11-07
description: Introduction to Content Collections
---

# My First Post

Content goes here...
7. 导入并使用
import { allPosts } from "content-collections";

console.log(allPosts); // Fully typed!

结果:内容具备类型安全、自动补全、验证和 HMR。


关键规则

✅ 务必做到:
  1. 在 tsconfig.json 中添加路径别名 —— 导入正常工作所必需
  2. 将 .content-collections 添加到 .gitignore —— 不应提交生成的文件
  3. 使用 Standard Schema 验证器 —— 支持 Zod、Valibot、ArkType
  4. 在模式中包含 content 字段 —— 解析 frontmatter 所必需
  5. 在转换中等待 compileMDX —— MDX 编译是异步的
  6. 在 Vite 中将 contentCollections() 放在 react() 之后 —— 插件顺序很重要
❌ 切勿这样做:
  1. 提交 .content-collections 目录 —— 始终由系统生成,切勿提交
  2. 使用非标准验证器 —— 必须支持 StandardSchema 规范
  3. 配置变更后忘记重启开发服务器 —— 新集合需要重启
  4. 在异步操作中使用同步转换 —— 转换必须是异步的
  5. 重复包装路径别名 —— 使用 content-collections,而不是 ./content-collections
  6. 从错误的包导入 —— 配置使用 @content-collections/core,数据使用 content-collections

避免已知问题

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

错误:Cannot find module 'content-collections' or its corresponding type declarations

原因:缺少 TypeScript 路径别名配置。

预防方法:

添加到 tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "content-collections": ["./.content-collections/generated"]
    }
  }
}

在 VS Code 中重启 TypeScript 服务器:Cmd+Shift+P → “TypeScript: Restart TS Server”

来源:常见用户错误


问题 #2:Vite 不断重启

错误:开发服务器持续重启,陷入无限循环。

原因:Vite 监视 .content-collections 目录的变更,而这些变更会触发重新生成。

预防方法:

  1. 添加到 .gitignore:
.content-collections/
  1. 如果问题仍然存在,添加到 vite.config.ts:
export default defineConfig({
  server: {
    watch: {
      ignored: ["**/.content-collections/**"],
    },
  },
});

来源:GitHub Issue #591(TanStack Start)


问题 #3:转换后的类型未反映出来

错误:TypeScript 类型与转换后的文档不匹配。

原因: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;
};

来源:GitHub Issue #396


问题 #4-8:高级故障排查

references/advanced-troubleshooting.md 中涵盖了其他问题:

问题错误快速修复
#4集合未更新验证 glob 模式,重启开发服务器
#5MDX/Shiki 错误使用兼容的版本(shiki ^1.0.0)
#6MDX 路径别名失效在 MDX 导入中使用相对路径
#7验证错误不明确添加自定义 Zod 错误消息
#8Ctrl+C 无法停止使用 kill -9 或单独运行 watch 命令

配置模式

模式用例模板
基础博客单个集合,仅 Markdowntemplates/content-collections.ts
多集合文章 + 文档,嵌套文件夹templates/content-collections-multi.ts
转换函数计算字段(slug、readingTime)参见 references/transform-cookbook.md
MDX + React语法高亮、React 组件templates/content-collections-mdx.ts

有关详细的架构模式(日期、标签、验证),请加载 references/schema-patterns.md。


React 组件集成

在 React 中使用集合
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>
  );
}

渲染 MDX 内容
import { MDXContent } from "@content-collections/mdx/react";

export function BlogPost({ post }: { post: { mdx: string } }) {
  return (
    <article>
      <MDXContent code={post.mdx} />
    </article>
  );
}

Cloudflare Workers 部署

Content Collections 非常适合 Cloudflare Workers(仅在构建时使用,不需要运行时文件系统)。使用模板 templates/wrangler.toml 配置。

模式:vite build → wrangler deploy(Vite 插件会自动处理 content-collections)

有关详细的部署指南,请加载 references/deployment-guide.md。


附带的资源

模板(9 个可复制粘贴的文件)

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

脚本

init-content-collections.sh - 一条命令即可自动完成设置


依赖项

必需
{
  "devDependencies": {
    "@content-collections/core": "^0.12.0",
    "@content-collections/vite": "^0.2.7",
    "zod": "^3.23.8"
  }
}
可选(MDX)
{
  "devDependencies": {
    "@content-collections/markdown": "^0.1.4",
    "@content-collections/mdx": "^0.2.2",
    "shiki": "^1.0.0"
  }
}

官方文档


软件包版本(已于 2025-11-07 验证)

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

快速故障排查

问题解决方案
TypeScript 找不到模块在 tsconfig.json 中添加路径别名,重启 TS 服务
Vite 不断重启将 .content-collections/ 添加到 .gitignore
更改未生效重启开发服务器,验证 glob 模式
MDX 编译错误检查 Shiki 版本是否兼容
验证错误不明确添加自定义 Zod 错误消息

何时加载参考资料

参考资料加载时机……
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 架构定义集合
  • 已创建第一个带有 frontmatter 的内容文件
  • 已在 React 组件中导入集合
  • 已验证类型正常工作(自动补全)
  • 已测试热重载(更改内容文件)

评论

支持 Markdown