Last active
April 17, 2025 08:52
-
-
Save disintegrator/b4cd67d667efeec784208763d9fe5b11 to your computer and use it in GitHub Desktop.
Add a reading time estimate to all your Contentful rich text nodes in GatsbyJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.onCreateNode = async options => { | |
return Promise.all([ | |
require("./gatsby-onCreateNode-readingTime").onCreateNode(options) | |
// add your other onCreateNode functions here | |
]); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { documentToPlainTextString } from "@contentful/rich-text-plain-text-renderer"; | |
import readingTime from "reading-time"; | |
import { GatsbyNode } from "gatsby"; | |
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({ | |
node, | |
loadNodeContent, | |
actions | |
}) => { | |
const { internal } = node; | |
const { owner, mediaType } = internal; | |
if (mediaType !== "text/richtext" || owner !== "gatsby-source-contentful") { | |
return; | |
} | |
const doc = JSON.parse(await loadNodeContent(node)); | |
const text = documentToPlainTextString(doc); | |
const result = readingTime(text); | |
actions.createNodeField({ node, name: "readingTime", value: result }); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
contentfulBlogPost { | |
body { | |
fields { | |
readingTime { | |
text | |
minutes | |
time | |
words | |
} | |
} | |
} | |
} | |
} |
I get "SyntaxError: Unexpected token {" from gatsby-onCreateNode-readingTime.js
What version of gatsby-source-contentful are you using? I always get Error: Could not find function loadNodeContent for plugin gatsby-source-contentful
on line 15
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for creating this gist, it was instrumental in getting this adding to my Gatsby site. Great gist!