hast-util-to-html is a core utility within the unifiedjs ecosystem, designed to serialize a HAST (Hypertext Abstract Syntax Tree) into an HTML string. It is currently at version 9.0.5 and maintains an active release cadence, providing frequent patch updates and introducing major versions for significant breaking changes or feature additions. This utility is distinct from `rehype-stringify`, which acts as a higher-level wrapper for integrating with rehype plugins, while `hast-util-to-html` offers direct, granular control over the serialization process. Its primary differentiators include extensive options for configuring the output, enabling use cases from pretty-printing to minification, and its direct compatibility with HAST trees. It serves as the inverse operation to `hast-util-from-html`, providing a complete round-trip for HTML processing within the unifiedjs framework. The package adheres to modern JavaScript standards, being ESM-only since version 9.
npm install hast-util-to-htmlVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates creating a HAST tree and then serializing it into an HTML string using `toHtml` with default and custom options.
Upgrade Node.js to 16+ and migrate imports to ESM syntax (e.g., `import` instead of `require`). If migration is not possible, use `hast-util-to-html@8`.
Replace `options.entities` with `options.characterReferences` and adjust its properties accordingly (e.g., `useNamedReferences`, `omitOptionalSemicolons`).
Only use publicly documented exports. Avoid deep imports into `node_modules/hast-util-to-html`.
Ensure that `allowDangerousCharacters` and `allowDangerousHtml` are `false` (the default) unless you have thoroughly vetted the input source and understand the security implications. Sanitize or validate user-generated HAST trees before serialization.
Only enable `characterReferences.omitOptionalSemicolons` if you are specifically building a minifier and have tested its compatibility with your target environment. For general use, keep this option disabled.
Migrate your project to use ES modules (`import`/`export`) or switch to an older version of `hast-util-to-html` (e.g., v8) that supports CommonJS. Ensure your `package.json` specifies `"type": "module"` for ESM.
Ensure you are using named imports: `import { toHtml } from 'hast-util-to-html';`. Verify that `hast-util-to-html` is correctly installed and that the version is compatible with your code.Update your code to use the `characterReferences` option instead of `entities`. For example, `options: { characterReferences: { useNamedReferences: true } }`.