Skip to content

添加阅读时间

创建一个 remark 插件,将阅读时间属性添加到 Markdown 或 MDX 文件的 frontmatter 中。使用此属性可以显示每个页面的阅读时间。

¥Create a remark plugin which adds a reading time property to the frontmatter of your Markdown or MDX files. Use this property to display the reading time for each page.

¥Recipe

  1. Install Helper Packages

    Install these two helper packages:

    终端窗口
    npm install reading-time mdast-util-to-string
  2. Create a remark plugin.

    This plugin uses the mdast-util-to-string package to get the Markdown file’s text. This text is then passed to the reading-time package to calculate the reading time in minutes.

    remark-reading-time.mjs
    import getReadingTime from 'reading-time';
    import { toString } from 'mdast-util-to-string';
    export function remarkReadingTime() {
    return function (tree, { data }) {
    const textOnPage = toString(tree);
    const readingTime = getReadingTime(textOnPage);
    // readingTime.text will give us minutes read as a friendly string,
    // i.e. "3 min read"
    data.astro.frontmatter.minutesRead = readingTime.text;
    };
    }
  3. Add the plugin to your config:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import { remarkReadingTime } from './remark-reading-time.mjs';
    export default defineConfig({
    markdown: {
    remarkPlugins: [remarkReadingTime],
    },
    });

    Now all Markdown documents will have a calculated minutesRead property in their frontmatter.

  4. Display Reading Time

    If your blog posts are stored in a content collection, access the remarkPluginFrontmatter from the entry.render() function. Then, render minutesRead in your template wherever you would like it to appear.

    src/pages/posts/[slug].astro
    ---
    import { CollectionEntry, getCollection } from 'astro:content';
    export async function getStaticPaths() {
    const blog = await getCollection('blog');
    return blog.map(entry => ({
    params: { slug: entry.slug },
    props: { entry },
    }));
    }
    const { entry } = Astro.props;
    const { Content, remarkPluginFrontmatter } = await entry.render();
    ---
    <html>
    <head>...</head>
    <body>
    ...
    <p>{remarkPluginFrontmatter.minutesRead}</p>
    ...
    </body>
    </html>

    If you’re using a Markdown layout, use the minutesRead frontmatter property from Astro.props in your layout template.

    src/layouts/BlogLayout.astro
    ---
    const { minutesRead } = Astro.props.frontmatter;
    ---
    <html>
    <head>...</head>
    <body>
    <p>{minutesRead}</p>
    <slot />
    </body>
    </html>
Astro 中文网 - 粤ICP备13048890号