Astro 5 Content Layer(glob() loader)处理 Markdown 时只运行 remarkPlugins,不运行 rehypePlugins。任何 build-time 内容处理逻辑必须写成 remark 插件。
概述
Astro 5 的 Content Layer 与”页面 Markdown”(src/pages/*.md)走不同的渲染流水线。Content Layer 在 remark 阶段之后不再进入 rehype,而是直接序列化为 HTML。
因此 astro.config.ts 中的 rehypePlugins 对 Content Collections 无效,只对 src/pages/*.md 生效。
用法
所有需要在 build 时处理 Content Layer 内容的逻辑(wikilink 解析、数据注入、死链检测等)必须写成 remark 插件:
// astro.config.ts
export default defineConfig({
markdown: {
remarkPlugins: [
remarkWikiLinks, // ✅ 对 Content Layer 生效
],
rehypePlugins: [
rehypeWikiLinks, // ❌ 对 Content Layer 无效
],
},
});
remark 插件操作 MDAST(Markdown AST),通过修改节点的 data.hProperties 来控制最终生成的 HTML 属性。
注意事项
- 需要操作最终 HTML DOM 结构的场景(如包装特定元素),必须在 remark 阶段完成,不能依赖 rehype
- 修改 remark 插件后需清除 Astro 内容缓存:
rm -rf site/.astro/collections
版本说明
本页面基于 Astro 5.x(Content Layer API)。Astro 4 及之前使用不同的 Content Collections API,行为可能不同。
参见
- astro-remark-hproperties-data-injection
参考
- HAT-198 实现过程中遭遇,通过将
rehypeWikiLinks.ts改写为remarkWikiLinks.ts解决 - https://docs.astro.build/en/guides/content-collections/