Logo

dev-resources.site

for different kinds of informations.

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

Published at
12/29/2022
Categories
astro
markdown
javascript
webdev
Author
Surjith S M
Categories
4 categories in total
astro
open
markdown
open
javascript
open
webdev
open
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;
  };
}

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

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,
  },
});

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>

Done :)

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

Featured ones: