17 December 2022
•
views
how-to
Adding Reading Time to an Article
If you've ever viewed an article on Medium, you'll notice that the preview gives an estimated "read time". This feature is easily to implement using the reading-time
node package and our existing contentlayer configuration. Begin by installing reading-time
.
We will add reading time by adding a new computed field to our post model and defining the type for ReadingTime.
Define the ReadingTime Type
We previously kept our type definitions in /content/defintions
. Create a new file reading-time.ts
and then use contentlayer's defineNestedType
to create the new type.
Add the ReadingTime Computed Field
Next, open up the post definition file at /content/definitions/post.ts
and define the new computed field.
Now, we contentlayer generates the typesafe JSON, each post will have a new field called "readingTime" -- an object with two nested components; the minutes it takes to read, and the number of words.
You can then display in a component however you like, accessing those members as follows:
Metadata
Published
December 17, 2022
Tags
next.js, coding