DEV Community

Stiven Castillo
Stiven Castillo

Posted on

9 2

How to implement TOC in Astro?

I am writing (rewriting) my blog from Nextjs to Astro because I feel it's better to manage with Markdown files.

And one of the features I require in some of my posts or notes is to have a table of contents (TOC). Because some posts are quite long.

Looking in google I found a post where there were some instructions to do it, unfortunately the implementation is deprecated :(.

Here are the steps I followed to implement TOC in my posts (md and mdx):

Installation

npm i rehype-slug rehype-toc rehype-autolink-headings rehype-stringify remark-toc
Enter fullscreen mode Exit fullscreen mode

Create markdown.config.ts file

this because it needs to implement for md and mdx files.

import remarkToc from "remark-toc";
import rehypeToc from "rehype-toc";

export default {
  remarkPlugins: [[remarkToc, { tight: true, ordered: true }]],
  rehypePlugins: [
    [
      rehypeToc,
      {
        headings: ["h1", "h2", "h3"],
        cssClasses: {
          toc: "toc-post", 
          link: "toc-link", 
        },
      },
    ],
  ],
};

Enter fullscreen mode Exit fullscreen mode

Add to astro.config file

...
import markdownConfig from './markdown.config'

export default defineConfig({
  markdown: markdownConfig,
  integrations: [
    mdx({
      ...markdownConfig,
      extendPlugins: false,
    }),
  ]
});

Enter fullscreen mode Exit fullscreen mode

I hope it will be of great help.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
twitchingastronaut profile image
TwitchingAstronaut

Hey Great article.

is there a way to have this only show on certain pages and in certain positions (ie after Title)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay