Build Your First Rehype Plugin

Write two real plugins: one that changes the tree (lazy images) and one that reports problems (missing alt text).

A rehype plugin is just a function. If you can loop over an array, you can write one. This tutorial builds two useful plugins and explains each line.

The shape of a plugin

unified calls your plugin function when you .use() it, with the options you passed. The plugin returns a transformer: a function that receives the syntax tree and the virtual file.

JS
function myPlugin(options) {
  // runs once, when .use(myPlugin, options) is called
  return function (tree, file) {
    // runs for every document that is processed
  }
}

Install the helper used below to walk the tree:

Terminal
npm install rehype unist-util-visit vfile-reporter

Plugin 1: lazy-load images

Goal: add loading="lazy" to every <img> that does not set loading already, so authors can still opt out with loading="eager".

plugin-lazy-images.mjs
import {rehype} from 'rehype'
import {visit} from 'unist-util-visit'

/** Add loading="lazy" to every <img> that does not set loading already. */
function rehypeLazyImages() {
  return function (tree) {
    visit(tree, 'element', function (node) {
      if (node.tagName === 'img' && node.properties.loading === undefined) {
        node.properties.loading = 'lazy'
      }
    })
  }
}

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeLazyImages)
  .process('<img src="a.png" alt="A"><img src="b.png" alt="B" loading="eager">')

console.log(String(file))
Output node plugin-lazy-images.mjs
<img src="a.png" alt="A" loading="lazy"><img src="b.png" alt="B" loading="eager">

How it works:

  1. visit(tree, 'element', fn) calls fn for every element node, at any depth.
  2. Each element has a tagName and a properties object. HTML attributes appear here with DOM-style names.
  3. We mutate the node in place. Changing the tree is the whole point of a transformer; no return value is needed.

Plugin 2: report missing alt text

Some plugins do not change anything; they check. Instead of throwing errors, they add messages to the file, with the position of the offending node, so tools can print them like a linter:

plugin-alt-check.mjs
import {rehype} from 'rehype'
import {visit} from 'unist-util-visit'
import {reporter} from 'vfile-reporter'

/** Warn about images that have no alt attribute. Options: {severity}. */
function rehypeRequireAlt(options = {}) {
  const fatal = options.severity === 'error'
  return function (tree, file) {
    visit(tree, 'element', function (node) {
      if (node.tagName === 'img' && node.properties.alt === undefined) {
        const message = file.message('Image is missing an `alt` attribute', node)
        message.fatal = fatal
      }
    })
  }
}

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeRequireAlt)
  .process('<p>Logo: <img src="logo.svg"></p>\n<img src="ok.png" alt="">')

console.log(reporter(file))
Output node plugin-alt-check.mjs
1:10-1:30 warning Image is missing an `alt` attribute

⚠ 1 warning

Details worth noticing:

  • file.message(reason, node) attaches the node's position, so the report says 1:10-1:30: line 1, columns 10 to 30.
  • alt="" is valid (it marks decorative images), so only a missing attribute is reported. Checking === undefined rather than falsiness matters here.
  • The plugin accepts an option. Setting severity: 'error' marks messages as fatal, which makes the rehype CLI exit with an error, useful in CI.

Common building blocks

NeedPackage
Walk the tree, optionally skipping or stoppingunist-util-visit
Check element typeshast-util-is-element
Get the text content of a nodehast-util-to-string
Query with CSS selectorshast-util-select
Create new elements terselyhastscript (h('a', {href: '#x'}, 'text'))
Detect headings and their levelhast-util-heading-rank

Removing or replacing nodes

visit passes the node's index and parent to your callback. To remove a node, splice it out of parent.children and return the same index so the walk continues at the right place:

JS
visit(tree, 'element', function (node, index, parent) {
  if (node.tagName === 'font' && parent && typeof index === 'number') {
    parent.children.splice(index, 1, ...node.children) // unwrap <font>
    return index
  }
})

Packaging and sharing

  • Export the plugin as the default export of an ES module, like official plugins do.
  • Name the package rehype-something so the CLI can load it with --use.
  • Document what it changes, its options, and any security implications, then write tests that process small inputs and compare output strings.

The official “Create a rehype plugin” article on unifiedjs.com (opens in a new tab) walks through another example: a plugin that adds ids to headings.

Sources and further reading

Use ↑ ↓ to move, Enter to open.