DEV Community

Surjith S M
Surjith S M

Posted on

How to add an Estimated Reading Time to your Astro Blog with Javascript & Markdown Plugins

First, create the function in any folder. Eg: ./src/utils/readingTime.js. Now add the following code.

import getReadingTime from "reading-time";
import { toString } from "mdast-util-to-string";

/** Estimated Reading time */
export function remarkReadingTime() {
  return function (tree, { data }) {
    const textOnPage = toString(tree);
    const readingTime = getReadingTime(textOnPage);
    data.astro.frontmatter.estReadingTime = readingTime.minutes;
  };
}
Enter fullscreen mode Exit fullscreen mode

Next, You need to install the following packages:

npm install reading-time mdast-util-to-string
# or
pnpm add reading-time mdast-util-to-string
Enter fullscreen mode Exit fullscreen mode

The above npm plugins are used to convert the markdown to string and then calculate the reading time in minutes.

Now, open the astro.config.mjs file and add the following code.

import { defineConfig } from "astro/config";

import { remarkReadingTime } from "./src/utils/readingTime";

export default defineConfig({
  markdown: {
    remarkPlugins: [remarkReadingTime],
    extendDefaultPlugins: true,
  },
});
Enter fullscreen mode Exit fullscreen mode

That's it. Now each frontmatter will include an extra variable called estReadingTime which you can use later like:

---
const { frontmatter } = Astro.props;
---

<span>{frontmatter.estReadingTime} min read</span>
Enter fullscreen mode Exit fullscreen mode

Done :)

Checkout the Astro & plugin documentation for more detailed instructions and options.

Top comments (0)