Markdown AST to HTML AST Transformer
mdast-util-to-hast is a foundational utility within the unified (syntax-tree) ecosystem, designed to convert an mdast (Markdown Abstract Syntax Tree) into a hast (HTML Abstract Syntax Tree). It is currently stable at version 13.2.1 and receives frequent patch and minor updates, with major versions occurring less often but bringing significant breaking changes, such as the recent v13.0.0. This package is crucial for developers building tools that process Markdown and render it to HTML, acting as the bridge between the two AST formats. Key differentiators include its tight integration with the broader unified ecosystem, offering a programmatic way to transform content, and serving as the inverse to `hast-util-to-mdast`. It is also the underlying engine for higher-level plugins like `remark-rehype`, which provides an easier abstraction for similar conversion tasks. Its focus is purely on AST transformation, providing granular control over the conversion process.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to use `require()` to import mdast-util-to-hast in a CommonJS environment, while the package is ESM-only.fixSwitch to using ES module `import` syntax and ensure your project is configured for ESM (e.g., `"type": "module"` in `package.json`). -
TypeError: (0 , mdast_util_to_hast_1.toHast) is not a function
cause This error often occurs when mixing ESM and CJS, or when a bundler/transpiler incorrectly transforms ESM imports.fixEnsure consistent ESM usage throughout your project. If using TypeScript, check `tsconfig.json` for `module` and `moduleResolution` settings (e.g., `"module": "node16", "moduleResolution": "node16"`). -
Error: Cannot find module 'mdast-util-to-hast' or its corresponding type declarations.
cause The package is not installed, or Node.js module resolution is failing to locate it, possibly due to a misconfigured `exports` map or incorrect import path in older Node.js versions.fixRun `npm install mdast-util-to-hast`. Ensure Node.js 16+ is used if on v13+ of the library, and that your `tsconfig.json` (if applicable) aligns with ESM resolution. -
Argument of type '...' is not assignable to parameter of type 'MdastNode'.
cause Type incompatibility, often due to outdated `@types/mdast` or `@types/hast` packages, or passing an incorrect AST node structure.fixUpdate `@types/mdast` and `@types/hast` to match the major version used by `mdast-util-to-hast` (v13 requires compatible types). Ensure the input `tree` adheres to the `MdastNode` interface.
Warnings
- breaking Version 13.0.0 made the package ESM-only and removed CommonJS support. Projects must be configured to use ES modules.
- breaking Node.js 16 or higher is now required for mdast-util-to-hast v13 and above.
- breaking The behavior for footnote backreferences changed in v13.0.0 to better match GitHub's rendering. The `footnoteBackLabel` option now expects a function for i18n.
- breaking The return type of `toHast` changed in v13.0.0 to always return a node (specifically, an empty `root` node if input is empty).
- gotcha Double encoding of URLs was fixed in v12.2.4. Older versions might produce incorrectly encoded URLs, leading to broken links.
Install
-
npm install mdast-util-to-hast -
yarn add mdast-util-to-hast -
pnpm add mdast-util-to-hast
Imports
- toHast
const toHast = require('mdast-util-to-hast')import { toHast } from 'mdast-util-to-hast' - defaultFootnoteBackLabel
import toHast, { defaultFootnoteBackLabel } from 'mdast-util-to-hast'import { defaultFootnoteBackLabel } from 'mdast-util-to-hast' - Options
import { Options } from 'mdast-util-to-hast'import type { Options } from 'mdast-util-to-hast'
Quickstart
import { promises as fs } from 'node:fs';
import { toHtml } from 'hast-util-to-html';
import { fromMarkdown } from 'mdast-util-from-markdown';
import { toHast } from 'mdast-util-to-hast';
async function convertMarkdownToHtml(markdownFilePath: string): Promise<string> {
try {
const markdown = String(await fs.readFile(markdownFilePath));
const mdast = fromMarkdown(markdown);
const hast = toHast(mdast);
const html = toHtml(hast);
return html;
} catch (error) {
console.error(`Error converting markdown: ${error instanceof Error ? error.message : String(error)}`);
throw error;
}
}
// Example usage:
const exampleFilePath = './example.md';
const exampleMarkdown = `## Hello **World**!\n\nThis is a [link](https://example.com) and some *italic* text.\n\n1. Item one\n2. Item two`;
fs.writeFile(exampleFilePath, exampleMarkdown)
.then(() => convertMarkdownToHtml(exampleFilePath))
.then(html => console.log('Generated HTML:\n', html))
.catch(error => console.error('Overall process failed:', error));