toc()

Crea un plugin de TOC que extrae los encabezados del Markdown/MDX y rellena CompileResult.toc.

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

Firma

function toc(options?: TocPluginOptions): UnifastPlugin

Parámetros

options?

Configuración de la extracción del TOC

PropiedadTipoPor defectoDescripción
maxDepthnumber3Profundidad máxima de encabezado a incluir (1-6). Un valor de 3 incluye h1, h2 y h3.

Uso

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" },
// ]

Ejemplos

Extracción básica de encabezados

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" },
// ]

Limitar la profundidad

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" },
// ]

Renderizar una navegación de 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>
  );
}