rehype plugin to transform an image with alt text to a figure with caption
Important
Converting an image with alt text to a figure with caption is an escape hatch. Alt text, title, and captions have different intended purposes, and you should eventually enhance your content to adopt them.
This package is a unified (rehype) plugin that takes an image node with alt text (e.g., ![Alt text](path-to-image.jpg)
) and converts it to a figure element with caption.
<figure>
<img src="path-to-image.jpg" alt="Alt text">
<figcaption>Alt Text</figcaption>
</figure>
This package is ESM only.
In Node.js (16.0+), install with npm:
npm install @microflash/rehype-figure
For Node.js versions below 16.0, stick to 1.x.x versions of this plugin.
In Deno, with esm.sh:
import rehypeFigure from "https://esm.sh/@microflash/rehype-figure";
In browsers, with esm.sh:
<script type="module">
import rehypeFigure from "https://esm.sh/@microflash/rehype-figure?bundle";
</script>
Say we have the following module example.js
:
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkGfm from "remark-gfm";
import remarkRehype from "remark-rehype";
import rehypeFigure from "@microflash/rehype-figure";
import rehypeStringify from "rehype-stringify";
main()
async function main() {
const file = await unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeFigure)
.use(rehypeStringify)
.process("![Alt text](path-to-image.jpg)");
console.log(String(file));
}
Running that with node example.js
yields:
<figure>
<img src="path-to-image.jpg" alt="Alt Text">
<figcaption>Alt Text</figcaption>
</figure>
The default export is rehypeFigure
.
The following options are available. All of them are optional.
className
: class for the wrappedfigure
element
By default, no classes are added to the figure
element.