hast to ESTree (JSX) Transformer

3.1.3 · active · verified Sun Apr 19

hast-util-to-estree is a utility package within the unified/syntax-tree ecosystem designed to transform a HTML Abstract Syntax Tree (hast) into an ECMAScript Abstract Syntax Tree (estree) with JSX extensions. This is particularly useful for embedding HTML content as JSX within JavaScript, such as in MDX. The current stable version is 3.1.3, with releases occurring regularly, often involving minor updates to dependencies or new options, indicating active maintenance. Key differentiators include its specific focus on the hast-to-estree transformation, robust handling of JSX, support for embedded MDX nodes, and its adherence to the unist specification, making it a reliable component in pipelines involving content transformation and compilation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates transforming a raw HTML string into an ESTree (JavaScript AST) with JSX nodes, then rendering it to a JSX-compatible string using companion utilities.

import { read } from 'to-vfile'
import { fromHtml } from 'hast-util-from-html'
import { toEstree } from 'hast-util-to-estree'
import { toJs, jsx } from 'estree-util-to-js'

async function transformHtmlToJsx() {
  const htmlContent = `
<!doctype html>
<html lang=en>
<title>Example Page</title>
<h1>Hello, hast-util-to-estree!</h1>
<p style="color:red">This is a styled paragraph.</p>
</html>
  `

  // Convert HTML string to a hast tree
  const hast = fromHtml(htmlContent)

  // Convert hast tree to an estree (with JSX nodes)
  const estree = toEstree(hast)

  // Convert estree to a JavaScript string (with JSX syntax)
  const jsxOutput = toJs(estree, { handlers: jsx }).value

  console.log(jsxOutput)
}

transformHtmlToJsx().catch(console.error)

view raw JSON →