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
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.
Articles
12 articles in total
How to add an Estimated Reading Time to your Astro Blog with Javascript & Markdown Plugins
currently reading
Creating a Dark, Light, System (Auto) Toggle Switch in Astro
read article
How to activate boosted free plan from Sanity CMS (double the limits using coupons)
read article
React JS - Set State of Parent Component from Child
read article
3 Reasons why Gmail SMTP is not working with PHPMailer()
read article
[Solved] 2020: Pure Vanilla Javascript Smooth Scroll to Element on anchor tag click #id
read article
How to Hide Email Address from Bots yet Show it to Humans
read article
Unicode Character Reference
read article
Migrating from Bootstrap 4 to 5 - Read this before you upgrade!
read article
My Learnings from using Git along with VSCode
read article
How to Bypass Medium.com Paywall (Upgrade) and Read Full Article?
read article
My First ES6 Test Code - Trying Modules without compilers (Export, Import)
read article
Featured ones: