跳到主要内容
Ed. notes

04 内容管线:Markdown 如何变成结构化内容

长文 · 2026-11-12 · 合集第 5 / 10 篇

  • 内容管线
  • Markdown
  • Zod
  • 构建日志
第 5 / 10 篇 · 查看全部章节 → 当前:04 内容管线:Markdown 如何变成结构化内容

结论

这个站没有 CMS,也没有数据库。内容层只有一个入口:

content/ 里的 Markdown
  → 扫描候选文件
  → 解析 frontmatter
  → Zod 校验
  → 过滤草稿
  → 转成 NoteSummary
  → 聚合标签与系列

这些步骤都在 frontend/server/utils/content.ts。构建前的校验脚本也复用同一个文件,所以「开发时能打开」和「构建时能通过」用的是同一套规则,不存在两套解析逻辑。

问题与设计

内容分两类:

  • 短笔记放在 content/notes/,slug 由文件名或目录名决定;
  • 长文放在 content/articles/<系列>/,slug 写在 frontmatter 里。

两类内容共用一套 frontmatter 契约:

---
title: '一篇笔记'
summary: '一句话结论'
type: tool
date: 2026-11-12
tags: ['工具', 'MCP']
draft: true
---

必填字段是 title、summary、type、date、tags;series、repo、website、draft 可选;长文额外必填 slug。type 只能是 tool、repo、experiment 或 article,未知字段会被拒绝,用来发现拼写错误。

这里有三个容易忽略的设计点。

1. 日期必须在构建期校验

YAML 默认会把未加引号的 2026-02-30 解析成 Date,然后悄悄滚到 2026-03-02。如果只依赖 YAML 解析,错误日期会变成另一篇「看起来正常」的文章。

解决方式是用 JSON_SCHEMA 让日期保持字符串,再交给 Zod 和日历校验:

import { JSON_SCHEMA, load as loadYaml } from 'js-yaml'

const parsed = matter(source, {
  engines: {
    yaml: {
      parse: (input: string) => loadYaml(input, { schema: JSON_SCHEMA }) as Record<string, unknown>,
    },
  },
})

日期是否真实存在,由下面的 isValidDate() 判断,而不是让 Date 自动纠正。

2. 一次收集所有错误

读取内容时不会遇到第一个坏文件就退出,而是把问题推入 issues,最后统一抛出:

if (issues.length > 0) throw new ContentValidationError(issues)

这样新增一批文章时,能一次看到所有字段、路径和 slug 冲突,不用修一个、跑一次、再修下一个。

3. 草稿仍然参与校验

draft: true 只影响发布,不影响合法性。草稿仍然会被解析和校验,字段错误会让构建失败。这样不会出现「写的时候一直没校验,发布当天才发现日期写错」。

关键代码

frontmatter 契约

const frontmatterSchema = z
  .object({
    title: z.string().trim().min(1, '标题不能为空'),
    summary: z.string().trim().min(1, '摘要不能为空'),
    type: z.enum(CONTENT_TYPES, { message: '类型必须是 tool、repo、experiment 或 article' }),
    date: z
      .string()
      .regex(/^\d{4}-\d{2}-\d{2}$/, '日期格式必须是 YYYY-MM-DD')
      .refine(isValidDate, '日期不是有效日期'),
    tags: z
      .array(z.string().trim().min(1, '标签不能为空'))
      .min(1, '至少需要一个标签')
      .refine((tags) => new Set(tags).size === tags.length, '标签不能重复'),
    series: z.string().trim().min(1, '系列名不能为空').optional(),
    repo: z.string().url('仓库链接必须是有效 URL').optional(),
    website: z.string().url('官网链接必须是有效 URL').optional(),
    draft: z.boolean().optional(),
    slug: z
      .string()
      .regex(SLUG_PATTERN, 'slug 必须是小写 kebab-case,只包含字母、数字和连字符')
      .optional(),
  })
  .strict()

.strict() 是契约的一部分:多写一个 tag 或 drafts,构建会直接失败,而不是默默忽略。

扫描候选文件

笔记允许两种写法:content/notes/foo.md 和 content/notes/foo/index.md。扫描时把两种写法归一到同一个 slug,并检查重复:

if (entry.isFile() && entry.name.endsWith('.md')) {
  slug = entry.name.slice(0, -'.md'.length)
  file = join(notesDir, entry.name)
} else if (entry.isDirectory()) {
  file = join(notesDir, entry.name, 'index.md')
  if (!existsSync(file)) continue
  slug = entry.name
}

长文的扫描会把 content/articles/<系列>/ 下的一级 .md 全部收进来,包括作为系列第一篇的 00-目录.md;也支持 content/articles/ 根下的单文件。目录结构保持一眼能看懂,目录文章和其余文章走同一条管线。

扫描时顺便从目录名和文件名解析出两个字段:

/** 系列目录名就是系列 key:01-从0建小站 → 01-从0建小站。 */
export const deriveSeriesKey = (directoryName: string): string => directoryName

/** 从文件名解析阅读序号:05-部署-01-镜像与多阶段构建.md → 5。 */
export const parseOrdinal = (fileName: string): number | undefined => {
  const match = /^(\d{2})-/.exec(fileName)
  if (!match) return undefined
  return Number(match[1])
}

系列因此不需要写在正文 frontmatter 里,目录名就是唯一事实来源。正文如果写了 series,它只作为断言:与推导值不一致就阻止构建,不会出现「目录叫 A、正文写 B」的静默错位。

00-目录.md 不再特殊处理:它和系列内其他文章一样参与扫描、校验和渲染,slug 是 <文件夹名>-00,有自己的详情页。系列本身只是一次文件夹聚合——文件夹名 01-从0建小站 同时就是系列名,/series 只负责总览,系列介绍就是这篇目录文章的正文。

系列因此也没有独立的元数据。之前那种把 title、description、audience、outcomes 塞进 00-目录.md frontmatter 的做法已经删除;要写系列说明,直接写正文。

读、过滤、排序

export const loadAllContent = (options: LoadContentOptions): ContentNote[] => {
  const issues: ContentIssue[] = []
  const entries = [
    ...collectNotes(options.contentDir, issues),
    ...collectArticles(options.contentDir, issues),
  ]

  // 检查笔记和长文是否共用同一个 slug。
  const bySlug = new Map<string, string>()
  for (const entry of entries) {
    const existing = bySlug.get(entry.slug)
    if (existing) {
      issues.push({
        file: `${existing}, ${entry.file}`,
        message: `slug "${entry.slug}" 冲突,笔记和长文共用同一 URL 空间`,
      })
      continue
    }
    bySlug.set(entry.slug, entry.file)
  }

  if (issues.length > 0) throw new ContentValidationError(issues)

  return entries.sort(byDateDescending)
}

export const loadContent = (options: LoadContentOptions): ContentNote[] => {
  const entries = loadAllContent(options)
  if (options.includeDrafts) return entries
  return entries.filter((entry) => !entry.draft)
}

笔记和长文在 URL 上处于同一个空间,所以 slug 冲突检查必须放在合并之后。否则 /notes/foo 可能对应两篇内容。

聚合标签与系列

页面需要的数据不是「文件列表」,而是「卡片、标签和系列」。toNoteSummary() 去掉正文,只保留页面需要的字段:

export const toNoteSummary = (note: ContentNote): NoteSummary => ({
  slug: note.slug,
  title: note.title,
  summary: note.summary,
  type: note.type,
  date: note.date,
  tags: note.tags,
  series: note.series,
  ordinal: note.ordinal,
  repo: note.repo,
  website: note.website,
})

标签和系列在内存里统计:

export const aggregateTags = (notes: NoteSummary[]): TagAggregate[] => {
  const counts = new Map<string, number>()

  for (const note of notes) {
    for (const tag of note.tags) {
      counts.set(tag, (counts.get(tag) ?? 0) + 1)
    }
  }

  return [...counts.entries()]
    .map(([name, count]) => ({ name, count }))
    .sort(
      (first, second) =>
        second.count - first.count || first.name.localeCompare(second.name, 'zh-CN'),
    )
}

export const aggregateSeries = (notes: NoteSummary[]): SeriesAggregate[] => {
  const groups = new Map<string, NoteSummary[]>()

  for (const note of notes) {
    if (!note.series) continue
    const group = groups.get(note.series) ?? []
    group.push(note)
    groups.set(note.series, group)
  }

  return [...groups.entries()]
    .map(([name, groupedNotes]) => {
      const sorted = groupedNotes.sort(byOrdinal)

      return {
        name,
        count: sorted.length,
        notes: sorted,
        updatedAt: sorted.reduce(
          (latest, note) => (note.date > latest ? note.date : latest),
          sorted[0]?.date ?? '',
        ),
      }
    })
    .sort((first, second) => first.name.localeCompare(second.name))
}

列表按日期倒序,系列之间按文件夹名升序(01- → 06-),系列内按阅读序号正序(序号缺失时回退日期)。前者适合「最新内容」,后两者适合有先后关系的构建日志。

渲染与标题锚点

renderMarkdown() 除了返回 HTML,还收集正文里的二、三级标题,供文章页右侧的「本文目录」使用:

export const renderMarkdown = (note: ...): RenderedMarkdown => {
  const headings: Heading[] = []

  const html = markdown.render(note.body, {
    slug: note.slug,
    kind: note.kind ?? 'note',
    headings,
  })

  return { html, headings }
}

heading_open 渲染器被重写:遇到 h2 / h3 就生成 id、写回 token,并把 { id, text, level } 推进 headings。id 由标题文本推导,保留中文并加 h- 前缀避免和正文里的手写锚点冲突,同名标题自动追加 -1、-2。

章节序号不在这里加工。作者在 Markdown 里写 ## 01 / 为什么拆成多个阶段,渲染器原样输出;渲染器只负责给出可跳转的锚点。

验证

先跑内容校验:

cd frontend
npm run content:validate

还可以故意制造两个错误,确认错误会一起出现:

---
title: ''
summary: '故意写坏'
type: tool
date: 2026-02-30
tags: ['测试']
---

预期输出会包含文件和字段:

内容校验失败(2 项):
- notes/broken.md: title: 标题不能为空
- notes/broken.md: date: 日期不是有效日期

再验证草稿过滤:

  1. 在 content/notes/ 新增一篇 draft: true 的笔记;
  2. 打开 /notes,确认它没有出现;
  3. 打开 /rss.xml 和 /sitemap.xml,确认也没有它;
  4. 把 draft 改成 false,重启开发服务器,确认它出现。

内容层的单元测试在 frontend/tests/nuxt/content.spec.ts,可以单独跑:

npx vitest run tests/nuxt/content.spec.ts

边界

  • 没有数据库和增量索引,每次请求都会重新扫描、解析和校验全部内容;当前规模够用,内容量变大后需要缓存或预生成。
  • 没有分页、搜索和运行时编辑;标签和系列都是请求时聚合的结果。
  • 长文只扫描 content/articles/ 根下和 <系列>/ 下一级,不支持更深的嵌套。
  • 草稿仍参与校验,不能用 draft: true 逃避字段错误。
  • 日期保持字符串是有意为之,不要改回 YAML 默认解析。
  • 更细的规则和测试设计见 构建实践 的内容模型两篇。

下一篇看内容怎样离开文件系统:Nitro 接口怎样把结构化内容变成 JSON、HTML、图片和订阅文件。