blog.dopana

返回

你是否曾经编写过包含数十个标题的长markdown文档,却必须手动创建目录?或者每次添加新标题时,都必须手动更新链接列表?🤔

在这篇文章中,我将介绍remark-toc - 一个可以轻松为markdown自动生成目录(TOC)的插件。

为什么需要目录?#

想象一下你正在阅读一本500页的书却没有目录。你想找到关于特定主题的信息,但必须逐页翻阅。非常累人且耗时,对吧?

在技术文档中,会出现类似问题:

  1. 包含许多标题的长文档
  2. 难以找到特定内容
  3. 读者浪费时间导航
  4. 手动更新费力

remark-toc通过以下方式解决这个问题:

  • 自动化 - 从现有标题创建TOC
  • 自动更新 - 添加/编辑标题时,TOC自动更新
  • 高度可定制 - 可配置深度、跳过标题等
  • 易于集成 - 与unified/remark管道一起使用

Remark-toc如何工作?#

将remark-toc想象成一个智能的”图书管理员”。当你给它markdown文档时:

  1. 它找到特殊标题(默认是”Contents”或”TOC”)
  2. 它分析之后的所有标题
  3. 它创建指向每个标题的链接列表
  4. 它替换TOC标题和下一个标题之间的内容
Markdown文档remark-toc插件查找TOC标题分析之后的标题创建链接列表替换TOC内容具有完整TOC的Markdown

安装Remark-toc#

前提条件#

remark-toc是一个unified/remark插件,所以你需要:

  • Node.js 16+
  • npm或yarn
  • 已安装unified或remark

安装#

使用npm安装
npm install remark-toc
bash
使用yarn安装
yarn add remark-toc
bash
使用pnpm安装
pnpm add remark-toc
bash

[!TIP] remark-toc是ESM only,所以请确保你的项目使用ES模块。

基本使用#

简单示例#

假设你有文件example.md:

以及文件example.js:

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

运行后的结果:

配置选项#

remark-toc提供许多选项进行自定义:

使用options配置
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:

有序列表loose
await remark()
  .use(remarkToc, {ordered: true, tight: false})
  .process(file)
js

结果:

1. [历史](#历史)

   1. [发现](#发现)
   2. [名称和符号](#名称和符号)

2. [轨道](#轨道)
markdown

限制标题深度#

只包含到特定深度的标题:

限制深度为3
await remark()
  .use(remarkToc, {maxDepth: 3})
  .process(file)
js

这只在TOC中包含H1、H2、H3标题。

跳过特定标题#

从TOC中排除不需要的标题:

跳过References标题
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插件配合良好:

在HTML中创建可点击的TOC:

与rehype插件集成
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

完整管道#

Markdown输入remark-tocremark-rehyperehype-slugrehype-autolink-headingsHTML输出

在Next.js中使用#

与next.config.mjs一起#

与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一起#

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
  • 不要信任用户输入
使用rehype-sanitize清理
import rehypeSanitize from 'rehype-sanitize'

await remark()
  .use(remarkToc)
  .use(remarkRehype)
  .use(rehypeSanitize)  // 清理HTML
  .use(rehypeStringify)
  .process(file)
js

最佳实践#

1. 标题放置#

将TOC标题放在适当位置 - 通常在介绍之后:

# 标题

简要介绍...

## 目录

## 第1节
markdown

2. 合理深度#

不要将maxDepth设置得太深 - 通常3-4就足够:

// 好
{maxDepth: 3}

// 太深,TOC混乱
{maxDepth: 6}
js

3. 跳过不必要的标题#

跳过如”References”、“Appendix”之类的标题:

{skip: 'References|Appendix|Acknowledgments'}
js

4. Tight vs Loose#

  • tight: true 用于技术文档(紧凑)
  • tight: false 用于包含大量文本的文档(可读)

与其他解决方案的比较#

功能remark-toc手动TOCTOC生成器
自动化有无有
自动更新有无有
高度可定制有有有限
Remark集成有无无
维护有N/A变化

结论#

remark-toc对于任何编写长markdown文档的人来说都是有用的工具。它有助于:

  • 从标题自动创建TOC
  • 减少维护工作
  • 灵活自定义
  • 与unified生态系统轻松集成

[!TIP] 最佳实践:始终将remark-toc与rehype-slug和rehype-autolink-headings一起使用,以获得具有可点击链接的完整TOC。

参考文献#