你是否曾经编写过包含数十个标题的长markdown文档,却必须手动创建目录?或者每次添加新标题时,都必须手动更新链接列表?🤔
在这篇文章中,我将介绍remark-toc - 一个可以轻松为markdown自动生成目录(TOC)的插件。
为什么需要目录?#
想象一下你正在阅读一本500页的书却没有目录。你想找到关于特定主题的信息,但必须逐页翻阅。非常累人且耗时,对吧?
在技术文档中,会出现类似问题:
- 包含许多标题的长文档
- 难以找到特定内容
- 读者浪费时间导航
- 手动更新费力
remark-toc通过以下方式解决这个问题:
- 自动化 - 从现有标题创建TOC
- 自动更新 - 添加/编辑标题时,TOC自动更新
- 高度可定制 - 可配置深度、跳过标题等
- 易于集成 - 与unified/remark管道一起使用
Remark-toc如何工作?#
将remark-toc想象成一个智能的”图书管理员”。当你给它markdown文档时:
- 它找到特殊标题(默认是”Contents”或”TOC”)
- 它分析之后的所有标题
- 它创建指向每个标题的链接列表
- 它替换TOC标题和下一个标题之间的内容
安装Remark-toc#
前提条件#
remark-toc是一个unified/remark插件,所以你需要:
- Node.js 16+
- npm或yarn
- 已安装unified或remark
安装#
npm install remark-tocbashyarn add remark-tocbashpnpm add remark-tocbash[!TIP] remark-toc是ESM only,所以请确保你的项目使用ES模块。
基本使用#
简单示例#
假设你有文件example.md:
# 冥王星
冥王星是柯伊伯带中的一颗矮行星。
## 目录
## 历史
### 发现
在1840年代,勒维耶使用牛顿力学预测了...的位置
### 名称和符号
冥王星的名字来自冥界罗马神哈迪斯的希腊语 epithet...
### 附加信息
关于冥王星的一些附加信息...
## 轨道
冥王星的轨道周期约为248年...markdown以及文件example.js:
import {remark} from 'remark'
import remarkToc from 'remark-toc'
import {read} from 'to-vfile'
const file = await remark()
.use(remarkToc)
.process(await read('example.md'))
console.log(String(file))js运行后的结果:
# 冥王星
冥王星是柯伊伯带中的一颗矮行星。
## 目录
* [历史](#历史)
* [发现](#发现)
* [名称和符号](#名称和符号)
* [附加信息](#附加信息)
* [轨道](#轨道)
## 历史
### 发现
在1840年代,勒维耶使用牛顿力学预测了...的位置
### 名称和符号
冥王星的名字来自冥界罗马神哈迪斯的希腊语 epithet...
### 附加信息
关于冥王星的一些附加信息...
## 轨道
冥王星的轨道周期约为248年...markdown配置选项#
remark-toc提供许多选项进行自定义:
await remark()
.use(remarkToc, {
heading: 'Contents', // 要查找的标题(默认:'(table[ -]of[ -])?contents?|toc')
maxDepth: 3, // 最大标题深度(默认:6)
skip: 'References', // 跳过特定标题
tight: true, // 列表tight还是loose(默认:true)
ordered: false, // 有序列表还是无序列表(默认:false)
prefix: 'user-content-' // 链接的前缀
})
.process(file)js高级功能#
更改TOC标题#
如果你想使用其他标题而不是”Contents”:
await remark()
.use(remarkToc, {heading: 'Structure'})
.process(file)js这将查找”Structure”标题(不区分大小写)而不是”Contents”。
带间距的有序列表#
创建带项目间距的编号列表形式的TOC:
await remark()
.use(remarkToc, {ordered: true, tight: false})
.process(file)js结果:
1. [历史](#历史)
1. [发现](#发现)
2. [名称和符号](#名称和符号)
2. [轨道](#轨道)markdown限制标题深度#
只包含到特定深度的标题:
await remark()
.use(remarkToc, {maxDepth: 3})
.process(file)js这只在TOC中包含H1、H2、H3标题。
跳过特定标题#
从TOC中排除不需要的标题:
await remark()
.use(remarkToc, {skip: 'References|Acknowledgments'})
.process(file)js“References”和”Acknowledgments”标题不会出现在TOC中。
为链接添加前缀#
出于安全原因需要前缀时很有用:
await remark()
.use(remarkToc, {prefix: 'user-content-'})
.process(file)js结果:
* [历史](#user-content-历史)
* [发现](#user-content-发现)markdown与其他插件集成#
remark-toc与其他remark/rehype插件配合良好:
与rehype-slug和rehype-autolink-headings一起#
在HTML中创建可点击的TOC:
import {remark} from 'remark'
import remarkToc from 'remark-toc'
import remarkRehype from 'remark-rehype'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypeStringify from 'rehype-stringify'
await remark()
.use(remarkToc) // 创建TOC
.use(remarkRehype) // Markdown → HTML
.use(rehypeSlug) // 为标题添加ID
.use(rehypeAutolinkHeadings) // 添加锚点链接
.use(rehypeStringify) // HTML → string
.process(file)js完整管道#
在Next.js中使用#
与next.config.mjs一起#
import remarkToc from 'remark-toc'
import remarkGfm from 'remark-gfm'
const nextConfig = {
experimental: {
mdxRs: true,
},
mdxOptions: {
remarkPlugins: [
remarkGfm,
[remarkToc, {heading: 'Contents', maxDepth: 3}]
],
},
}
export default nextConfigjs与MDX组件一起#
import remarkToc from 'remark-toc'
import {MDXRemote} from 'next-mdx-remote/rsc'
export default function Post({content}) {
return (
<MDXRemote
source={content}
options={{
mdxOptions: {
remarkPlugins: [[remarkToc, {heading: 'Contents'}]]
}
}}
/>
)
}jsx在Astro中使用#
与astro.config.mjs一起#
import { defineConfig } from 'astro/config'
import mdx from '@astrojs/mdx'
import remarkToc from 'remark-toc'
export default defineConfig({
integrations: [mdx()],
markdown: {
remarkPlugins: [
[remarkToc, {heading: 'Contents', maxDepth: 3}]
]
}
})js安全考虑#
[!WARNING] remark-toc将现有节点复制到TOC中,如果markdown包含恶意内容,可能导致XSS攻击。
危险示例:
## 目录
## Bravo<script>alert(1)</script>markdown结果:
- [Bravo<script>alert(1)</script>](#bravoscriptalert1script)markdown解决方案:
- 处理前清理markdown
- 转换为HTML时使用
rehype-sanitize - 不要信任用户输入
import rehypeSanitize from 'rehype-sanitize'
await remark()
.use(remarkToc)
.use(remarkRehype)
.use(rehypeSanitize) // 清理HTML
.use(rehypeStringify)
.process(file)js最佳实践#
1. 标题放置#
将TOC标题放在适当位置 - 通常在介绍之后:
# 标题
简要介绍...
## 目录
## 第1节markdown2. 合理深度#
不要将maxDepth设置得太深 - 通常3-4就足够:
// 好
{maxDepth: 3}
// 太深,TOC混乱
{maxDepth: 6}js3. 跳过不必要的标题#
跳过如”References”、“Appendix”之类的标题:
{skip: 'References|Appendix|Acknowledgments'}js4. Tight vs Loose#
tight: true用于技术文档(紧凑)tight: false用于包含大量文本的文档(可读)
与其他解决方案的比较#
| 功能 | remark-toc | 手动TOC | TOC生成器 |
|---|---|---|---|
| 自动化 | 有 | 无 | 有 |
| 自动更新 | 有 | 无 | 有 |
| 高度可定制 | 有 | 有 | 有限 |
| Remark集成 | 有 | 无 | 无 |
| 维护 | 有 | N/A | 变化 |
结论#
remark-toc对于任何编写长markdown文档的人来说都是有用的工具。它有助于:
- 从标题自动创建TOC
- 减少维护工作
- 灵活自定义
- 与unified生态系统轻松集成
[!TIP] 最佳实践:始终将remark-toc与rehype-slug和rehype-autolink-headings一起使用,以获得具有可点击链接的完整TOC。