withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.8k stars 2.49k forks source link

Markdown plugin rehype-autolink-headings does not work with `.md` files #5001

Closed devgioele closed 2 years ago

devgioele commented 2 years ago

What version of astro are you using?

1.4.4

Are you using an SSR adapter? If so, which one?

None

What package manager are you using?

npm

What operating system are you using?

Linux

Describe the Bug

The Markdown rehype plugin rehype-autolink-headings does only work with MDX files, while it should also work with Markdown files. The attached example shows that heading IDs and links are injected on page /mdx, but not on page /md.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/withastro-astro-ofyb1r

Participation

devgioele commented 2 years ago

After experimenting with the tests of the Astro codebase, I understood that the heading IDs that Astro generates automatically are added after all plugins are applied. Using rehype-slug before rehype-autolink-headings solved the issue.

The documentation explains it actually, but it is easy to miss.

ryuheechul commented 1 year ago

Few quick tips for (whom found this issue by googling) who's trying to use rehype-autolink-headings for the first time like me.

First you will need that rehyp-slug thing @devgioele mentioned 👍🏼.

And by default what's added by this plugin is <a ...><span class="icon icon-link" /></span></a> which is not visible unless you have CSS configured to render something for .icon-link or .icon. You might need/want to add display: inline-block; (css) or .inline-block (tailwind) too.

mrchantey commented 2 months ago

An example implementation:

// astro.config.mjs
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
export default defineConfig({
  markdown: {
    rehypePlugins: [
      rehypeSlug,
      [rehypeAutolinkHeadings, { behavior: 'append' }]
  }
})
// style.css

html {
  scroll-behavior: smooth;
}

span.icon-link::before {
  content: '#';
  font-size: 0.8em;
  margin-left: 10px;
}