An alternative way to calculate reading time without full blog post rendering
Published onJanuary 03, 2024Β·2 minutes read
Table of Contents
Intro
I recently tried to move my website to Astro, but I wanted to keep most of the existing features.
As you can see in the blog page, the list of blog posts include the time it takes to read each post.
This feature in Astro requires quite a bit of work to be implemented.
The βofficialβ way
If you followed the official docs recipe, first you need to install 2 packages:
Then, you create a custom Remark plugin to add the reading time to the frontmatter property of your blog posts.
And finally, you add it to your remark plugins array.
The problem
By following these steps, you need to access the remarkPluginFrontmatter property from your post. And to do so, you first need to render the whole blog post content using the entry.render() function.
Besides, as I told you before, I wanted to display this information in the blog posts list too, so it was a bit tedious to render the whole markdown for every post before being able to access the minutesRead property.
And even though I tried to do it this way, for some reason the minutesRead property was not really added to the frontmatter. Not sure if I did something wrong, but it simply didnβt work for me.
My approach (or solution)
By doing a small modification to the custom Remark plugin originally suggested in Astro docs, I created an utility function to calculate the reading time.
It requires installing and using an additional dependency though:
It, instead of requiring rendering the blog post first, just takes the body property that already comes with the blog post entry.
Now, you no longer need to add the custom Remark plugin to astro.config.mjs
Instead, use a BlogPost component in your blog page:
Then call the getReadingTime function from the component file and use that property anywhere:
Conclusion
While the official Astro method works and is valid, it does require rendering each post.
A simpler alternative using existing data (the body property) and a custom utility function, avoids the extra step and is more efficient to calculate the reading time.
To summarize, by creating customized solutions, it is often possible to improve upon official methods by eliminating unnecessary steps. especially when your use case differs and you look for a more straightforward approach.