gatsby-plugin-mdx with rehype-autolink-headers only working with wrap option

839 Views Asked by At

I am trying to get my site setup with Gatsby + MDX. I am looking at the documentation here and want to make use of the autolink-header-option. I have tried using the rehype and remark plugins for this, but I can only get the Rehype plugin to work and only with the wrap option. I would much prefer the GitHub (default) style with the link coming before the title.

I am using the below config in gatsby-config.js and cleared .cache and public after updating the file to be sure nothing was cached. Also I am not getting any errors, everything builds and runs successfully, there just is not any link to the headers.

{
  resolve: `gatsby-plugin-mdx`,
  options: {
    rehypePlugins: [
      // To pass options, use a 2-element array with the
      // configuration in an object in the second element
      require("rehype-autolink-headings"),
    ],
  },
},

UPDATE

After trying multiple configurations, the way I was able to get it working as expected was with a different plugin config.

{
  resolve: `gatsby-plugin-mdx`,
  options: {
    gatsbyRemarkPlugins: [ `gatsby-remark-autolink-headers` ],
    plugins: [ `gatsby-remark-autolink-headers` ],
  },
}

Both gatsbyRemarkPlugins and plugins are required as per: https://github.com/gatsbyjs/gatsby/issues/15486

1

There are 1 best solutions below

2
On

The README for rehype-autolink-headings mentions that:

This package works with headings that have IDs. One way to add IDs to headings is by using remark-slug before this plugin.

Changing your config to the following should fix it:

{
  resolve: `gatsby-plugin-mdx`,
  options: {
    rehypePlugins: [
      require("rehype-slug"),
      // To pass options, use a 2-element array with the
      // configuration in an object in the second element
      require("rehype-autolink-headings"),
    ],
  },
},

In fact, the documentation you linked to has this additional require line as well, but it doesn't clarify what it is used for.