DEV Community

Stiven Castillo
Stiven Castillo

Posted on

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.

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)