rehype-autolink-headings 使用教程
项目介绍
rehype-autolink-headings
是一个用于在 HTML 文档中为标题添加链接的插件。这个插件特别适用于较长的文档,用户可以通过链接直接跳转到文档的特定部分。该插件可以与 rehype-slug
插件结合使用,后者用于自动为标题生成 ID。
项目快速启动
安装
该包仅支持 ESM。在 Node.js (版本 16+) 中,使用 npm 安装:
npm install rehype-autolink-headings
在 Deno 中,使用 esm.sh:
import rehypeAutolinkHeadings from 'https://esm.sh/rehype-autolink-headings@7'
使用示例
以下是一个简单的使用示例:
import { unified } from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const processor = unified()
.use(rehypeParse)
.use(rehypeAutolinkHeadings)
.use(rehypeStringify)
const html = `
<h1>标题1</h1>
<h2>标题2</h2>
<h3>标题3</h3>
`
processor.process(html).then(file => {
console.log(String(file))
})
应用案例和最佳实践
应用案例
- 文档网站:在文档网站中,用户可以通过点击标题链接快速跳转到文档的特定部分,提高用户体验。
- 博客文章:在博客文章中,为每个标题添加链接,方便读者分享特定内容。
最佳实践
- 结合
rehype-slug
:使用rehype-slug
自动为标题生成 ID,然后使用rehype-autolink-headings
添加链接。 - 自定义链接样式:通过配置选项自定义链接的样式,使其与文档风格一致。
典型生态项目
- rehype-slug:自动为标题生成 ID。
- rehype-highlight:为代码块添加语法高亮。
- rehype-toc:为文档生成目录。
这些插件可以与 rehype-autolink-headings
结合使用,构建功能丰富的文档处理工具链。