Isomorphic HTML to HAST Tree Converter

2.0.0 · active · verified Sun Apr 19

hast-util-from-html-isomorphic is a utility package for the hast ecosystem that efficiently converts HTML strings into a hast (HTML Abstract Syntax Tree) tree. Designed for isomorphic applications, it intelligently uses hast-util-from-dom in browser environments, leveraging native DOM parsing APIs for a significantly smaller bundle size, and falls back to hast-util-from-html in Node.js. This approach prioritizes minimal client-side footprint, making it ideal for web components, static site generators, or libraries that need to process HTML both server-side and client-side without a large parser overhead. A key characteristic is that it does not preserve positional information (line, column, offset) from the original HTML string, a deliberate trade-off for its performance and size benefits. The current stable version is 2.0.0, which updated its @types/hast dependency. This package is part of the syntax-tree unified ecosystem and generally sees updates as underlying dependencies or major features warrant, rather than on a strict time-based cadence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing HTML strings into HAST trees, showing the difference between parsing as a document (default) and as a fragment, highlighting the common usage patterns.

import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic';
import type { Root } from 'hast';

// Example 1: Parsing a simple HTML fragment
// When `fragment: true`, it parses only the content within the `<body>` or directly as children of `root`.
const fragmentHtml = '<h1>Hello, world!</h1><p>This is a paragraph.</p>';
const fragmentTree: Root = fromHtmlIsomorphic(fragmentHtml, { fragment: true });

console.log('--- Parsed as Fragment ---');
console.log(JSON.stringify(fragmentTree, null, 2));

// Example 2: Parsing a full HTML document
// By default (or with `fragment: false`), it expects a complete document structure.
// Unopened `html`, `head`, and `body` elements will be implicitly added.
const documentHtml = '<title>My Doc</title><body><h1>Document Title</h1><p>More content.</p></body>';
const documentTree: Root = fromHtmlIsomorphic(documentHtml);

console.log('\n--- Parsed as Document ---');
console.log(JSON.stringify(documentTree, null, 2));

view raw JSON →