How to add an estimated reading time in AstroPaper
Updated: | at 14:53
As the Astro docs say, we can use remark plugin to add a reading time property in our frontmatter. However, for some reason, we can’t add this feature by following what stated in Astro docs. Therefore, to achieve this, we have to tweak a little bit. This post will demonstrate how we can do that.
Step (2) Create remark-reading-time.mjs file under utils directory
Step (3) Add the plugin to astro.config.ts
Step (4) Add readingTime to blog schema (src/content/config.ts)
Step (5) Create a new file called getPostsWithRT.ts under src/utils directory.
Step (6) Refactor getStaticPaths of /src/pages/posts/[slug].astro as the following
Step (7) Refactor PostDetails.astro like this. Now you can access and display readingTime in PostDetails.astro
Access reading time outside of PostDetails (optional)
By following the previous steps, you can now access readingTime frontmatter property in you post details page. Sometimes, this is exactly what you want. If so, you can skip to the next section. However, if you want to display “estimated reading time” in index, posts, and technically everywhere, you need to do the following extra steps.
Step (1) Update utils/getSortedPosts.ts as the following
Step (2) Make sure to refactor every file which uses getSortedPosts function. You can simply add await keyword in front of getSortedPosts function.
Files that use getSortedPosts function are as follow
src/pages/index.astro
src/pages/posts/index.astro
src/pages/rss.xml.ts
src/pages/posts/index.astro
src/pages/posts/[slug].astro
src/utils/getPostsByTag.ts
All you have to do is like this
Now you can access readingTime in other places besides PostDetails
Displaying reading time (optional)
Since you can now access readingTime in your post details (or everywhere if you do the above section), it’s up to you to display readingTime wherever you want.
But in this section, I’m gonna show you how I would display readingTime in my components. This is optional. You can ignore this section if you want.
Step (1) Update Datetime component to display readingTime
Step (2) Then, pass readingTime props from its parent component.
file: Card.tsx
file: PostDetails.tsx
Conclusion
By following the provided steps and tweaks, you can now incorporate this useful feature into your content. I hope this post helps you adding readingTime in your blog. AstroPaper might include reading time by default in future releases. 🤷🏻♂️