Skip to content
This repository has been archived by the owner on Feb 27, 2022. It is now read-only.

feat: add 'reading-time' and word count #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/next-mdx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"gray-matter": "^4.0.2",
"hasha": "^5.2.2",
"next-mdx-remote": "^2.1.3",
"node-cache": "^5.1.2"
"node-cache": "^5.1.2",
"reading-time": "^1.3.0"
},
"peerDependencies": {
"next": ">= 10.0.0",
Expand Down
6 changes: 6 additions & 0 deletions packages/next-mdx/src/get-nodes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { promises as fs } from "fs"
import matter from "gray-matter"
import hasha from "hasha"
import readingTime from "reading-time"
import { GetStaticPropsContext } from "next"
import { Pluggable, Compiler } from "unified"
import renderToString from "next-mdx-remote/render-to-string"
Expand Down Expand Up @@ -181,6 +182,11 @@ export async function getFileData(file: MdxFile): Promise<MdxFileData> {

const { content, data: frontMatter } = matter(raw)

const word_count = content.split(/\s+/gu).length
const reading_time = readingTime(content)
frontMatter.reading_time = reading_time
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

frontMatter.word_count = word_count

const fileData: MdxFileData = {
hash,
content,
Expand Down
2 changes: 2 additions & 0 deletions packages/next-mdx/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ test("gets a node using slug", async () => {
const post = await getNode("post", "post-one")
expect(post.frontMatter.title).toBe("Post One")
expect(post.url).toBe("/blog/post-one")
expect(post.frontMatter.word_count).toBe(71)
expect(post.frontMatter.reading_time.text).toBe("1 min read")

const author = await getNode("author", "john-doe")
expect(author.frontMatter.name).toBe("John Doe")
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10487,6 +10487,11 @@ readdirp@~3.5.0:
dependencies:
picomatch "^2.2.1"

reading-time@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/reading-time/-/reading-time-1.3.0.tgz#d13e74431589a4a9038669f24d5acbc08bbb015d"
integrity sha512-RJ8J5O6UvrclfZpcPSPuKusrdRfoY7uXXoYOOdeswZNtSkQaewT3919yz6RyloDBR+iwcUyz5zGOUjhgvfuv3g==

rebass@^4.0.7:
version "4.0.7"
resolved "https://registry.yarnpkg.com/rebass/-/rebass-4.0.7.tgz#0a84e5558750c1f416c3baf41ec4c7fc8d64a98a"
Expand Down