Skip to content

Add Reading Time to Starlight

2 min read

This recipes will show one possible way to add reading time to Starlight.

  1. Start by installing all packages that need:

    Terminal window
    npm add reading-time mdast-util-to-string
  2. Create reading time remark plugin:

    plugins/remark-reading-time.mjs
    import getReadingTime from 'reading-time'
    import { toString } from 'mdast-util-to-string'
    export function remarkReadingTime() {
    return function (tree, { data }) {
    const textOnPage = toString(tree)
    const readingTime = getReadingTime(textOnPage)
    // readingTime.text will give us minutes read as a friendly string,
    // i.e. "3 min read"
    data.astro.frontmatter.minutesRead = readingTime.text
    }
    }
  3. Change Starlight’s page title:

    src/components/PageTitle.astro
    ---
    /*
    * Implement the source code according to Astro Docs:
    * https://github.com/withastro/docs/blob/main/src/components/starlight/PageTitle.astro
    */
    import { render } from 'astro:content';
    import { Icon } from '@astrojs/starlight/components';
    import type { Props } from '@astrojs/starlight/props';
    const { entry } = Astro.props;
    const { data } = Astro.props.entry;
    const { remarkPluginFrontmatter } = await render(entry);
    ---
    <div class='wrapper'>
    <h1 id='_top'>
    <span>{data.title}</span>
    </h1>
    <p class='sl-flex'>
    <Icon name='seti:clock' size='1.2em' />
    {remarkPluginFrontmatter.minutesRead}
    </p>
    </div>
    <style>
    .wrapper {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    }
    h1 {
    display: flex;
    flex-wrap: wrap;
    color: var(--sl-color-white);
    font-size: var(--sl-text-h1);
    font-weight: 600;
    line-height: var(--sl-line-height-headings);
    }
    p {
    gap: 0.5rem;
    align-items: center;
    text-decoration: none;
    color: var(--sl-color-gray-3);
    }
    </style>
  4. Add the plugin to your config and override Starlight’s page title:

    astro.config.mjs
    import { defineConfig } from 'astro/config'
    import { remarkReadingTime } from './plugins/remark-reading-time.mjs'
    export default defineConfig({
    markdown: {
    remarkPlugins: [remarkReadingTime],
    },
    ...
    export default defineConfig({
    integrations: [
    starlight({
    components: {
    PageTitle: './src/components/PageTitle.astro',
    },
    }),
    ],
    })
  1. Add reading time