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.
Top comments (0)