How rehype works

rehype looks simple from the outside: HTML goes in, HTML comes out. Knowing what happens in between makes everything else, from choosing plugins to writing your own, much easier.

rehype is a unified processor

unified is a general engine for processing content as syntax trees. It does not know anything about HTML or Markdown by itself; plugins teach it. The rehype package is a shortcut for a unified processor with two plugins already attached:

unified-explicit.mjs
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'

const file = await unified()
  .use(rehypeParse, {fragment: true})
  .use(rehypeStringify)
  .process('<p>Unclosed <em>emphasis<p>Second paragraph')

console.log(String(file))
Output node unified-explicit.mjs
<p>Unclosed <em>emphasis</em></p><p><em>Second paragraph</em></p>

That example builds the same thing rehype() gives you, by hand: rehype-parse turns HTML into a tree, and rehype-stringify turns a tree into HTML. Notice how the unclosed <em> and <p> were repaired, exactly as a browser would. That is the WHATWG HTML parsing algorithm at work (rehype-parse uses the parse5 library).

The same engine powers remark (Markdown) and retext (natural language). This is why a rehype plugin and a remark plugin look alike, and why you can convert between them inside one pipeline.

The three phases

parsetext → tree, by the parser (rehype-parse)
runtree → tree, by transformer plugins
stringifytree → text, by the compiler (rehype-stringify)

.process() runs all three. You can also call the phases separately: .parse() returns a tree without running plugins, .run(tree) runs the transformers, and .stringify(tree) serializes. That is handy when you want the tree itself, for example to analyze a page.

The hast tree

hast (Hypertext Abstract Syntax Tree) is the format rehype uses. It is plain JSON-compatible data. Here is the tree for one short paragraph:

inspect-tree.mjs
import {rehype} from 'rehype'

const tree = rehype()
  .data('settings', {fragment: true})
  .parse('<p class="note">Hi <b>there</b></p>')

// Drop positional info so the structure is easier to read.
const strip = (node) => {
  const {position, ...rest} = node
  if (rest.children) rest.children = rest.children.map(strip)
  return rest
}

console.log(JSON.stringify(strip(tree), null, 2))
Output node inspect-tree.mjs
{
  "type": "root",
  "children": [
    {
      "type": "element",
      "tagName": "p",
      "properties": {
        "className": [
          "note"
        ]
      },
      "children": [
        {
          "type": "text",
          "value": "Hi "
        },
        {
          "type": "element",
          "tagName": "b",
          "properties": {},
          "children": [
            {
              "type": "text",
              "value": "there"
            }
          ]
        }
      ]
    }
  ],
  "data": {
    "quirksMode": false
  }
}

The node types you will meet most:

TypeRepresentsKey fields
rootThe whole document or fragmentchildren
elementAn HTML elementtagName, properties, children
textText contentvalue
comment<!-- … -->value
doctype<!doctype html>none

Two details trip people up. First, attributes live in properties and use DOM-style names: class becomes className (an array of class names), for becomes htmlFor, and onclick becomes onClick. Second, whitespace between elements is real text nodes; that is why formatting and minifying are tree transformations too. Every node also carries a position with line and column, which the example strips for readability.

Walking the tree

Because the tree is plain data, you rarely write recursive code by hand. The unist-util-visit utility calls a function for every node of a given type:

visit-tree.mjs
import {rehype} from 'rehype'
import {visit} from 'unist-util-visit'

const tree = rehype()
  .data('settings', {fragment: true})
  .parse('<article><h1>Title</h1><p>One <a href="/a">link</a> and <a href="/b">another</a>.</p></article>')

const counts = {}
visit(tree, 'element', function (node) {
  counts[node.tagName] = (counts[node.tagName] || 0) + 1
})

console.log(counts)
Output node visit-tree.mjs
{ article: 1, h1: 1, p: 1, a: 2 }

Utilities like this are shared across the ecosystem: unist-util-* packages work on any unified tree, and hast-util-* packages are HTML-specific (for example hast-util-select for CSS selectors or hast-util-to-string for text content).

Virtual files and messages

A processor works on a VFile: the contents, an optional path, arbitrary data, and a list of messages. Plugins report problems by adding messages with positions, and tools like vfile-reporter print them. This is how linting-style plugins work without throwing exceptions; see the plugin tutorial for an example.

Plugins in one paragraph

A plugin is a function. unified calls it once when you .use() it, passing options. If it returns a function, that function is a transformer: it receives the tree and the file, and changes the tree in place (or returns a new one). Order matters, because each transformer sees the tree as the previous ones left it. Presets, such as rehype-preset-minify, are objects that bundle several plugins with settings.

Summary

  • rehype = unified + rehype-parse + rehype-stringify.
  • Processing has three phases: parse, run, stringify.
  • The tree format is hast: roots, elements, text, comments and doctypes.
  • Plugins are functions that transform the tree, in order.

Sources and further reading

Use ↑ ↓ to move, Enter to open.