How to add an Estimated Reading Time to your Astro Blog with Javascript & Markdown Plugins
Surjith S M
Posted on December 29, 2022
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.
π πͺ π
π©
Surjith S M
Posted on December 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
astro How to add an Estimated Reading Time to your Astro Blog with Javascript & Markdown Plugins
December 29, 2022