系列 · 建站记

一篇 mdx 的旅程

2026-10-31约 1 分钟MDX

从落笔到页面

以 posts/hello.mdx 为例。这个文件从写完到能访问,中间发生三件事:

  1. lib/atlas.js 用 import.meta.glob 读进所有 mdx 的 frontmatter, 和目录的 atlas.json 合成一张登记表;
  2. pages/[...slug].astro 按登记表生成路由——文件在 posts/hello.mdx, 地址就是 /posts/hello/,产物是 dist/posts/hello/index.html;
  3. 渲染时包上 PostLayout:系列章节左栏挂目录树,题头带系列徽章、日期、 标签;散篇不挂树,上一篇/下一篇按日期相邻。

frontmatter 长这样。有个小坑我踩过:日期要带引号,不然 YAML 会把它解析成 Date 对象,校验器直接报格式错误。

---
title: 文章标题
desc: 一句话摘要(列表与 RSS 用)
date: "2026-10-31"
tags: [检索词]
order: 1        # 系列章节必填;分组里与兄弟同级排序
draft: true     # 草稿:不产出、不进列表与 RSS
---

mdx 和纯 markdown 的区别就一条:正文里可以 import 组件。开篇那篇 hello 里 的章节标题 SectionHead,就是正文里一行 import 拿来用的——写文章时能用上 整套站点积木,这是当初选 mdx 而不是纯 markdown 的主要原因。