toc()

Tạo plugin TOC trích xuất các tiêu đề từ Markdown/MDX và đưa vào CompileResult.toc.

import { toc } from "@unifast/node";

Chữ ký

function toc(options?: TocPluginOptions): UnifastPlugin

Tham số

options?

Cấu hình trích xuất TOC

Thuộc tínhKiểuMặc địnhMô tả
maxDepthnumber3Độ sâu tiêu đề tối đa được bao gồm (1-6). Giá trị 3 bao gồm h1, h2 và h3.

Cách dùng

import { compile, toc } from "@unifast/node";

const result = compile(md, {
  plugins: [
    toc({
      maxDepth: 3,
    }),
  ],
});

console.log(result.toc);
// [
//   { depth: 1, text: "Introduction", slug: "introduction" },
//   { depth: 2, text: "Getting Started", slug: "getting-started" },
//   { depth: 3, text: "Installation", slug: "installation" },
// ]

Ví dụ

Trích xuất tiêu đề cơ bản

import { compile, toc } from "@unifast/node";

const md = `# Introduction

## Getting Started

### Installation

## API Reference

### compile()

### hastToHtml()`;

const result = compile(md, { plugins: [toc()] });

console.log(result.toc);
// [
//   { depth: 1, text: "Introduction", slug: "introduction" },
//   { depth: 2, text: "Getting Started", slug: "getting-started" },
//   { depth: 3, text: "Installation", slug: "installation" },
//   { depth: 2, text: "API Reference", slug: "api-reference" },
//   { depth: 3, text: "compile()", slug: "compile" },
//   { depth: 3, text: "hastToHtml()", slug: "hasttohtml" },
// ]

Giới hạn độ sâu

import { compile, toc } from "@unifast/node";

const result = compile(md, {
  plugins: [toc({ maxDepth: 2 })],
});

console.log(result.toc);
// Only h1 and h2 headings are included
// [
//   { depth: 1, text: "Introduction", slug: "introduction" },
//   { depth: 2, text: "Getting Started", slug: "getting-started" },
//   { depth: 2, text: "API Reference", slug: "api-reference" },
// ]

Render điều hướng TOC

import { compile, toc } from "@unifast/node";

const result = compile(md, { plugins: [toc()] });

function TableOfContents() {
  return (
    <nav>
      <ul>
        {result.toc.map((entry) => (
          <li key={entry.slug} style={{ marginLeft: (entry.depth - 1) * 16 }}>
            <a href={`#${entry.slug}`}>{entry.text}</a>
          </li>
        ))}
      </ul>
    </nav>
  );
}