The built-in reading time calculator in gatsby-transformer-remark
You probably don't need gatsby-remark-reading-time
In the ECMAScript world, there's a module for everything. A common, and well-documented way to calculate a Medium-style estimated reading time in Gatsby is to use the gatsby-remark-reading-time
plugin. This works great, but is probably unnecessary, because if you're using gatsby-transformer-remark
(as you probably are, if you're parsing .md
or .mdx
files), you can use built-in timeToRead
field.
This field doesn't appear to have been explicitly documented yet, but it is referenced in the rundown of Gatsby's internals. It's also clearly defined in the gatsby-transformer-remark
source code.
timeToRead: {
type: `Int`,
resolve(markdownNode) {
return getHTML(markdownNode).then(html => {
let timeToRead = 0
const pureText = sanitizeHTML(html, { allowTags: [] })
const avgWPM = 265
const wordCount =
_.words(pureText).length +
_.words(pureText, /[\p{sc=Katakana}\p{sc=Hiragana}\p{sc=Han}]/gu)
.length
timeToRead = Math.round(wordCount / avgWPM)
if (timeToRead === 0) {
timeToRead = 1
}
return timeToRead
})
},
},
There appears to have been an attempt to allow the average WPM and the text counted to be configured, but this was later rolled back due to unexpectedly high memory usage and slow builds.