@jcayzac/astro-rehype-frontmatter-reading-stats
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

@jcayzac/astro-rehype-frontmatter-reading-stats

Word count and estimated reading time for Astro Markdown/MDX content.

license npm version npm downloads bundle

Rehype plugin to add the word count and estimated reading time to the frontmatter of Markdown documents loaded by Astro.

Installation

# pnpm
pnpm add @jcayzac/astro-rehype-frontmatter-reading-stats

# bun
bunx add @jcayzac/astro-rehype-frontmatter-reading-stats

# npm
npx add @jcayzac/astro-rehype-frontmatter-reading-stats

# yarn
yarn add @jcayzac/astro-rehype-frontmatter-reading-stats

# deno
deno add npm:@jcayzac/astro-rehype-frontmatter-reading-stats

Usage

Add the plugin to your Astro project's astro.config.mjs:

import { defineConfig } from 'astro/config'
import readingStats from '@jcayzac/astro-rehype-frontmatter-reading-stats'

export default defineConfig({
  markdown: {
    rehypePlugins: [
      readingStats(),
    ]
  }
})

The frontmatter of your Markdown documents will have new fields added:

  • wordCount: the approximate number of words in the document.

  • readingTime: the estimated reading time in minutes, rounded.

    [!TIP] if you want an ISO-8601 duration, for example to use in a <time> HTML element, simply use `PT${Math.round(readingTime)}M`.

You can access those in your Astro components:

---
import type { FrontmatterReadingStats } from '@jcayzac/astro-rehype-frontmatter-reading-stats'
import type { CollectionEntry } from 'astro:content'

interface Props {
  article: CollectionEntry<'articles'>
}

const { article } = props as Props
const { Content, remarkPluginFrontmatter } = await article.render()
const { wordCount, readingTime } = remarkPluginFrontmatter as FrontmatterReadingStats
---
<div>
  <h1>{article.title}</h1>
  <p>{wordCount} words</p>
  <time datetime={`PT${Math.round(readingTime)}M`}>A {readingTime}min read</time>
  <Content />
</div>

Like it? Buy me a coffee!

If you like anything here, consider buying me a coffee using one of the following platforms:

GitHub Sponsors Revolut Wise Ko-Fi PayPal


Package Sidebar

Install

npm i @jcayzac/astro-rehype-frontmatter-reading-stats

Weekly Downloads

20

Version

0.1.0

License

MIT

Unpacked Size

12.7 kB

Total Files

7

Last publish

Collaborators

  • jcayzac