hast-util-to-xast

raw JSON →
3.0.1 verified Sat May 09 auth: no javascript

Utility to transform a hast (HTML) syntax tree into a xast (XML) syntax tree. v3.0.1, ESM-only, fully typed with TypeScript. Supports automatic SVG namespace switching and embedded MDX nodes. Commonly used for EPUB generation. Requires Node.js 16+. Replaced old direct `space` argument with `options.space` in v3.

error TypeError: toXast is not a function
cause Using default import instead of named import (e.g., `import toXast from 'hast-util-to-xast'`). Package only exports named export.
fix
Change import to import { toXast } from 'hast-util-to-xast'.
error Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/hast-util-to-xast/index.js from /path/to/project/index.js not supported.
cause Using require() on an ESM-only package.
fix
Use import() or switch to ESM in your project (package.json type: module).
error TypeError: The "original" argument must be of type function. Received an instance of Object
cause Passing a string as second argument instead of an options object in v3+.
fix
Change toXast(hast, 'svg') to toXast(hast, { space: 'svg' }).
breaking Removed direct `space` string argument; use `options.space` instead.
fix Pass `{ space: 'svg' }` instead of `'svg'` as second argument.
breaking Changed to ESM-only. No CommonJS support starting from v3.
fix Use `import { toXast } from 'hast-util-to-xast'` or dynamic `import()`.
breaking Dropped support for Node.js < 16.
fix Upgrade Node.js to version 16 or later.
gotcha When space is 'html', SVG elements are automatically detected and switched to SVG namespace, but custom XML namespaces not supported.
fix Use explicit `xmlns` attributes for non-SVG custom namespaces (may not be preserved).
npm install hast-util-to-xast
yarn add hast-util-to-xast
pnpm add hast-util-to-xast

Parses HTML with hast-util-from-html, converts to xast, then serializes to XML string.

import { fromHtml } from 'hast-util-from-html'
import { toXast } from 'hast-util-to-xast'
import { toXml } from 'xast-util-to-xml'

const html = `<!DOCTYPE html><title>Hello</title><h1>World</h1>`
const hast = fromHtml(html)
const xast = toXast(hast, { space: 'html' })
const xml = toXml(xast)
console.log(xml)
// <?xml version="1.0" encoding="utf-8"?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Hello</title></head><body><h1>World</h1></body></html>