hast-util-to-parse5

8.0.1 · active · verified Sun Apr 19

hast-util-to-parse5 is a utility within the unified (syntax-tree) ecosystem designed to convert a HAST (Hypertext Abstract Syntax Tree) into a parse5 AST (Abstract Syntax Tree). It is currently at version 8.0.1 and receives updates as part of the broader unified collective, with major versions typically introducing significant changes and minor/patch versions addressing features and fixes. This package differentiates itself by avoiding the use of parse5 adapters, which the developers state reduces code weight and fragility. It is primarily used when there's a specific need to generate a parse5 AST from an existing HAST tree, though its inverse, `hast-util-from-parse5`, is often more commonly employed. The library is ESM-only and requires Node.js 16 or newer since its 8.x release line. Users should be aware of potential cross-site scripting (XSS) risks if the input HAST tree is not properly sanitized, as highlighted in its security considerations.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to convert a complex HAST (Hypertext Abstract Syntax Tree) to a parse5 AST using `toParse5` and specify the `space` option.

import { toParse5 } from 'hast-util-to-parse5';
import type { Element, Text, Root } from 'hast';

const hastTree: Root = {
  type: 'root',
  children: [
    {
      type: 'element',
      tagName: 'html',
      properties: { lang: 'en' },
      children: [
        {
          type: 'element',
          tagName: 'head',
          properties: {},
          children: [
            { type: 'element', tagName: 'title', properties: {}, children: [{ type: 'text', value: 'Hello' }] as Text[] }
          ]
        } as Element,
        {
          type: 'element',
          tagName: 'body',
          properties: {},
          children: [
            { type: 'element', tagName: 'h1', properties: {}, children: [{ type: 'text', value: 'World!' }] as Text[] },
            { type: 'element', tagName: 'p', properties: {}, children: [{ type: 'text', value: 'This is a paragraph.' }] as Text[] }
          ]
        } as Element
      ]
    } as Element
  ]
};

// Convert the hast tree to a parse5 AST
const parse5Tree = toParse5(hastTree, { space: 'html' });

console.log(JSON.stringify(parse5Tree, null, 2));

/* Example of what the output parse5Tree might look like (truncated):
{
  "nodeName": "html",
  "tagName": "html",
  "attrs": [
    {
      "name": "lang",
      "value": "en"
    }
  ],
  "namespaceURI": "http://www.w3.org/1999/xhtml",
  "childNodes": [
    {
      "nodeName": "head",
      "tagName": "head",
      // ... more child nodes ...
    },
    {
      "nodeName": "body",
      "tagName": "body",
      // ... more child nodes ...
    }
  ]
}
*/

view raw JSON →