@atomictech/rehype-toc

中文文档
3.1.3发布于 2021/03/31MITTypeScriptCommonJS零依赖近 30 天下载 1864

A rehype plugin that adds a table of contents (TOC) to the page

原始使用文档
文档目录8 节
  1. Features
  2. Example
  3. Installation
  4. Usage
  5. Options
  6. Contributing
  7. License
  8. Big Thanks To

Table of Contents plugin for Rehype

A rehype plugin that adds a table of contents (TOC) to the page

Cross-Platform Compatibility Build Status

Coverage Status Dependencies

npm License Buy us a tree

Features

  • Adds a <nav> and <ol> list outlining all headings on the page
  • Combine with rehype-slug to create links to each heading
  • Ignores headings outside of <main> if it exists
  • You can customize which headings are included (defaults to <h1> - <h6>)
  • You can customize the CSS classes on every TOC element
  • Hooks give you complete customization of the generated HTML

Example

input.html
Here's the original HTML file. There are three levels of headings (<h1> - <h3>), and none of them have IDs.

<html>
  <body>
    <h1>Apple Pie Recipe</h1>
    <p>This is the world's best apple pie recipe...</p>

    <div>
      <h2>Filling</h2>
      <p>The filling is the best part...</p>

      <h3>Preparing the apples</h3>
      <p>Cut the apples into 1/4 inch slices...</p>

      <h3>Preparing the spice mix</h3>
      <p>In a mixing bowl, combine sugar, cinnamon...</p>
    </div>

    <div>
      <h2>Crust</h2>
      <p>How to make the perfect flaky crust...</p>

      <h3>Preparing the dough</h3>
      <p>Combine flour, sugar, salt...</p>

      <h3>The criss-cross top</h3>
      <p>Cut the top crust into 1/2 inch strips...</p>
    </div>
  </body>
</html>

example.js
This script reads the input.html file above writes the results to output.html (shown below). The script uses unified, rehype-parse, rehype-slug, and rehype-stringify.

const unified = require("unified");
const parse = require("rehype-parse");
const slug = require("rehype-slug");
const toc = require("@jsdevtools/rehype-toc");
const stringify = require("rehype-stringify");
const fs = require("fs");

async function example() {
  // Create a Rehype processor with the TOC plugin
  const processor = unified()
    .use(parse)
    .use(slug)
    .use(toc)
    .use(stringify);

  // Read the original HTML file
  let inputHTML = await fs.promises.readFile("input.html");

  // Process the HTML, adding heading IDs and Table of Contents
  let outputHTML = await processor.process(inputHTML);

  // Save the new HTML
  await fs.promises.writeFile("output.html", outputHTML);
}

output.html
Here's the HTML that gets created by the above script. Notice that a table of contents has been added at the top of the <body>, with links to each of the headings on the page. The headings also now have IDs, thanks to rehype-slug.

<html>
  <body>
    <nav class="toc">
      <ol class="toc-level toc-level-1">
        <li class="toc-item toc-item-h1">
          <a class="toc-link toc-link-h1" href="#apple-pie-recipe">
            Apple Pie Recipe
          </a>

          <ol class="toc-level toc-level-2">
            <li class="toc-item toc-item-h2">
              <a class="toc-link toc-link-h2" href="#filling">
                Filling
              </a>

              <ol class="toc-level toc-level-3">
                <li class="toc-item toc-item-h3">
                  <a class="toc-link toc-link-h3" href="#preparing-the-apples">
                    Preparing the apples
                  </a>
                </li>
                <li class="toc-item toc-item-h3">
                  <a class="toc-link toc-link-h3" href="#preparing-the-spice-mix">
                    Preparing the spice mix
                  </a>
                </li>
              </ol>
            </li>

            <li class="toc-item toc-item-h2">
              <a class="toc-link toc-link-h2" href="#crust">
                Crust
              </a>

              <ol class="toc-level toc-level-3">
                <li class="toc-item toc-item-h3">
                  <a class="toc-link toc-link-h3" href="#preparing-the-dough">
                    Preparing the dough
                  </a>
                </li>
                <li class="toc-item toc-item-h3">
                  <a class="toc-link toc-link-h3" href="#the-criss-cross-top">
                    The criss-cross top
                  </a>
                </li>
              </ol>
            </li>
          </ol>
        </li>
      </ol>
    </nav>

    <h1 id="apple-pie-recipe">Apple Pie Recipe</h1>
    <p>This is the world's best apple pie recipe...</p>

    <div>
      <h2 id="filling">Filling</h2>
      <p>The filling is the best part...</p>

      <h3 id="preparing-the-apples">Preparing the apples</h3>
      <p>Cut the apples into 1/4 inch slices...</p>

      <h3 id="preparing-the-spice-mix">Preparing the spice mix</h3>
      <p>In a mixing bowl, combine sugar, cinnamon...</p>
    </div>

    <div>
      <h2 id="crust">Crust</h2>
      <p>How to make the perfect flaky crust...</p>

      <h3 id="preparing-the-dough">Preparing the dough</h3>
      <p>Combine flour, sugar, salt...</p>

      <h3 id="the-criss-cross-top">The criss-cross top</h3>
      <p>Cut the top crust into 1/2 inch strips...</p>
    </div>
  </body>
</html>

Installation

You can install Rehype TOC via npm.

npm install @jsdevtools/rehype-toc

You'll probably want to install unified, rehype-parse, rehype-stringify, and rehype-slug as well.

npm install unified rehype-parse rehype-stringify rehype-slug

Usage

Using the Rehype TOC plugin requires an understanding of how to use Unified and Rehype. Here is an excelleng guide to learn the basics.

The Rehype TOC plugin works just like any other Rehype plugin. Pass it to the .use() method, optionally with an options object.

const unified = require("unified");
const toc = require("@jsdevtools/rehype-toc");

// Use the Rehype TOC plugin with its default options
unified().use(toc);

// Use the Rehype TOC plugin with custom options
unified().use(toc, {
  headings: ["h1", "h2"],     // Only include <h1> and <h2> headings in the TOC
  cssClasses: {
    toc: "page-outline",      // Change the CSS class for the TOC
    link: "page-link",        // Change the CSS class for links in the TOC
  }
});

Options

The Rehype TOC plugin supports the following options:

OptionTypeDefaultDescription
navbooleantrueDetermines whether the table of contents is wrapped in a <nav> element.
positionstring"afterbegin"The position at which the table of contents should be inserted, relative to the <main> or <body> element. Can be "beforebegin", "afterbegin", "beforeend", or "afterend". See the insertAdjacentElement() docs for an explanation of each value.
placeholderstringThe optional placeholder string to replace with the table of contents.
headingsarray of stringsh1, h2, h3, h4, h5, h6The HTML heading tags to include in the table of contents
cssClasses.tocstringtocThe CSS class name for the top-level <nav> or <ol> element that contains the whole table of contents.
cssClasses.liststringtoc-levelThe CSS class name for all <ol> elements in the table of contents, including the top-level one.
cssClasses.listItemstringtoc-itemThe CSS class name for all <li> elements in the table of contents.
cssClasses.linkstringtoc-linkThe CSS class name for all <a> elements in the table of contents.
customizeTOCfunction(toc)Allows you to customize the table of contents before it is added to the page.

The function receives the TOC node tree and can modify it in any way you want. Or you can return a new node tree to use instead. Or return false to prevent the the TOC from being added to the page.
customizeTOCItemfunction(toc, heading)Allows you to customize each item in the table of contents before it is added to the page.

The function receives the TOC item's node tree and the heading node that it refers to. You can modify the nodes in any way you want. Or you can return a new node tree to use instead. Or return false to prevent the the TOC from being added to the page.

Contributing

Contributions, enhancements, and bug-fixes are welcome! Open an issue on GitHub and submit a pull request.

Building

To build the project locally on your computer:

  1. Clone this repo
    git clone https://github.com/JS-DevTools/rehype-toc.git

  2. Install dependencies
    npm install

  3. Build the code
    npm run build

  4. Run the tests
    npm test

License

Rehype TOC is 100% free and open-source, under the MIT license. Use it however you want.

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Big Thanks To

Thanks to these awesome companies for their support of Open Source developers ❤

Travis CI SauceLabs Coveralls

版本与发布记录

@atomictech/rehype-toc 共发布 4 个版本,首次发布于 2021/01/08;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.1.3latest2021/03/315 年前
3.1.22021/01/255 年前
3.1.12021/01/135 年前
3.1.02021/01/085 年前

关于 @atomictech/rehype-toc 的常见问题

@atomictech/rehype-toc 是什么?

A rehype plugin that adds a table of contents (TOC) to the page

如何安装 @atomictech/rehype-toc?

在项目目录运行 npm install @atomictech/rehype-toc,或使用 pnpm add / yarn add / bun add。

@atomictech/rehype-toc 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@atomictech/rehype-toc 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@atomictech/rehype-toc 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=10。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@atomictech/rehype-toc 可以商用吗?

@atomictech/rehype-toc 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@atomictech/rehype-toc 的下载量有多少?

根据 npm 官方下载统计,@atomictech/rehype-toc 在 2026/10/07 – 2026/11/05 这 30 天内被下载 1,864 次,日均约 62 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@atomictech/rehype-toc 还在维护吗?

最新版本 3.1.3 发布于 2021/03/31(5 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/01/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。