Markdown AST to HTML AST Transformer

13.2.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This example demonstrates the full workflow from reading a Markdown file to converting it to an HTML string using mdast-util-to-hast and related utilities.

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));

view raw JSON →