refactor: use rehype-slug and rehype-autolink-headings

This commit is contained in:
Timothy Lin
2021-08-22 17:13:14 +08:00
parent 51feadc0db
commit 0e34d80287
4 changed files with 43 additions and 27 deletions

View File

@ -6,8 +6,6 @@ import readingTime from 'reading-time'
import { visit } from 'unist-util-visit'
import getAllFilesRecursively from './utils/files'
// Remark packages
import remarkSlug from 'remark-slug'
import remarkAutolinkHeadings from 'remark-autolink-headings'
import remarkGfm from 'remark-gfm'
import remarkFootnotes from 'remark-footnotes'
import remarkMath from 'remark-math'
@ -15,6 +13,8 @@ import remarkCodeTitles from './remark-code-title'
import remarkTocHeadings from './remark-toc-headings'
import remarkImgToJsx from './remark-img-to-jsx'
// Rehype packages
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypeKatex from 'rehype-katex'
import rehypePrismPlus from 'rehype-prism-plus'
@ -87,8 +87,6 @@ export async function getFileBySlug(type, slug) {
// plugins in the future.
options.remarkPlugins = [
...(options.remarkPlugins ?? []),
remarkSlug,
remarkAutolinkHeadings,
[remarkTocHeadings, { exportRef: toc }],
remarkGfm,
remarkCodeTitles,
@ -98,6 +96,8 @@ export async function getFileBySlug(type, slug) {
]
options.rehypePlugins = [
...(options.rehypePlugins ?? []),
rehypeSlug,
rehypeAutolinkHeadings,
rehypeKatex,
[rehypePrismPlus, { ignoreMissing: true }],
() => {

View File

@ -1,11 +1,12 @@
import { visit } from 'unist-util-visit'
import { slug } from 'github-slugger'
export default function remarkTocHeadings(options) {
return (tree) =>
visit(tree, 'heading', (node, index, parent) => {
options.exportRef.push({
value: node.children[0].value || node.children[1].value,
url: node.children[0].url || node.children[1].url,
value: node.children[0].value,
url: '#' + slug(node.children[0].value),
depth: node.depth,
})
})