import { defineMdastPlugin } from "satteri" import { toString } from "mdast-util-to-string" import getReadingTime from "reading-time" /** * 把阅读时长写进 frontmatter(minutes / words)。 * * 页面侧通过 render(entry).remarkPluginFrontmatter 读这两个值, * 与 unified 时期完全一致,所以 posts/[...slug].astro 不用改。 */ export const readingTime = defineMdastPlugin({ name: "reading-time", after(root, ctx) { // 用 mdast-util-to-string 而不是 ctx.textContent: // 后者只拼接纯 text 节点,会漏掉代码块、行内代码、公式、图片 alt, // 导致字数比迁移前少一截(实测 LaTeX 那篇 830 → 488 字)。 const text = toString(root) const stats = getReadingTime(text) const frontmatter = ctx.data.astro.frontmatter frontmatter.minutes = Math.max(1, Math.round(stats.minutes)) frontmatter.words = stats.words }, })