rehype.ts 831 B

123456789101112131415161718192021222324252627
  1. import { visit } from 'unist-util-visit'
  2. import { mdxAnnotations } from 'mdx-annotations'
  3. import rehypeMdxTitle from 'rehype-mdx-title'
  4. import rehypeAutolinkHeadings from 'rehype-autolink-headings'
  5. import { slugifyWithCounter } from '@sindresorhus/slugify'
  6. import { toString } from 'mdast-util-to-string'
  7. import rehypeExternalLinks from 'rehype-external-links'
  8. function rehypeSlugify() {
  9. return tree => {
  10. let slugify = slugifyWithCounter()
  11. visit(tree, 'element', node => {
  12. if ((node.tagName === 'h2' || node.tagName === 'h3') && !node.properties.id) {
  13. node.properties.id = slugify(toString(node))
  14. }
  15. })
  16. }
  17. }
  18. export const rehypePlugins = [
  19. mdxAnnotations.rehype,
  20. rehypeSlugify,
  21. rehypeAutolinkHeadings,
  22. [rehypeExternalLinks, { target: '_blank', rel: ['nofollow'] }],
  23. rehypeMdxTitle,
  24. ]