mdast-util-toc is a utility within the unified (specifically mdast) ecosystem for programmatically generating a table of contents from a markdown abstract syntax tree (AST). It provides a `toc` function that processes an `mdast` tree, identifying headings and constructing a new `mdast` list node representing the table of contents. The package is currently stable at version 7.1.0, with minor and patch releases occurring periodically, and major versions introducing breaking changes like ESM-only support or Node.js version bumps. Key differentiators include its tight integration with the `mdast` AST format, allowing for flexible programmatic manipulation, and its robust options for controlling the TOC generation, such as specifying heading depth (`minDepth`, `maxDepth`), skipping specific headings, and defining parent node types. It's often used indirectly via `remark-toc` for simpler integration into `remark` pipelines, which handles the injection of the generated TOC back into the document. Its focus is purely on AST transformation, making it highly composable.
npm install mdast-util-tocVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to import the `toc` function and use it to generate a table of contents from a simple mdast syntax tree, configured to include headings up to depth 2.
Migrate your project to ESM and use `import { toc } from 'mdast-util-toc'`. If using Node.js, ensure your package.json has `"type": "module"` or files end in `.mjs`.Upgrade your Node.js environment to version 16 or newer. Use a Node.js version manager like `nvm` to switch.
Update your code to expect `undefined` instead of `null` when checking for the absence of a TOC result, e.g., `if (table === undefined) { /* handle no TOC */ }`.Always use the documented public exports, such as `import { toc } from 'mdast-util-toc'`, and avoid deeply importing from internal paths like `mdast-util-toc/lib/some-internal-module`.Review your `toc` options. If you previously filtered headings by depth after generation, consider using the `minDepth` option (along with `maxDepth`) for more efficient, built-in filtering, e.g., `toc(tree, { minDepth: 2, maxDepth: 4 })`.Change your import statement to `import { toc } from 'mdast-util-toc';` and ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`).Before accessing properties like `map`, check if the `table` result is not `undefined` (or `null` for older versions): `const table = toc(tree); if (table && table.map) { /* process table */ }`Ensure you are running Node.js 16+ and your project's `package.json` specifies `"type": "module"` if you are using `.js` files for ESM. Otherwise, use `.mjs` file extensions. Verify `mdast-util-toc` is correctly installed.
No dependency data recorded yet.