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.
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:
npm install rehype unist-util-visit vfile-reporterPlugin 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".
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))<img src="a.png" alt="A" loading="lazy"><img src="b.png" alt="B" loading="eager">How it works:
visit(tree, 'element', fn)callsfnfor every element node, at any depth.- Each element has a
tagNameand apropertiesobject. HTML attributes appear here with DOM-style names. - 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:
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))1:10-1:30 warning Image is missing an `alt` attribute
⚠ 1 warningDetails worth noticing:
file.message(reason, node)attaches the node's position, so the report says1:10-1:30: line 1, columns 10 to 30.alt=""is valid (it marks decorative images), so only a missing attribute is reported. Checking=== undefinedrather 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
| Need | Package |
|---|---|
| Walk the tree, optionally skipping or stopping | unist-util-visit |
| Check element types | hast-util-is-element |
| Get the text content of a node | hast-util-to-string |
| Query with CSS selectors | hast-util-select |
| Create new elements tersely | hastscript (h('a', {href: '#x'}, 'text')) |
| Detect headings and their level | hast-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:
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-somethingso 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.