The rehype-resolution Node.js package provides a rehype plugin for inserting
srcset attributes into
img elements. rehype is a unified HTML processor.
The srcset attribute of the
img element enables responsive images. This plugin inserts a
srcset for resolution switching, allowing different resolutions at the same size.
If you're supporting multiple display resolutions, but everyone sees your image at the same real-world size on the screen, you can allow the browser to choose an appropriate resolution image by using srcset with x-descriptors and without sizes — a somewhat easier syntax!
The rehype-resolution plugin inserts a set of possible image sources (
@3x), following Apple’s naming convention for image size and resolution. Users have to produce these images and make them available at the according paths.
The transformation is only applied for file names ending with
@1x.*. That’s the marker for the transform. Elements with an existing
srcset attribute are ignored.
Generating a static website from Markdown, I want crisp images on all devices.
Inserting the srcset attribute
We have an image at three resolutions,
email@example.com. Let’s assume we don’t control the HTML, maybe it’s generated from Markdown, leaving us with HTML like this.
To let the browser pick the optimal image, this transform inserts the
srcset attribute for three resolutions, allowing us to keep referencing the image with a single URI in our Markdown or whatever HTML source we might have.
srcset into HTML fragment.
const parse =const resolution =const stringify =const unified =const log = console
$ node example.js <img src="firstname.lastname@example.org" srcset="email@example.com 1x, firstname.lastname@example.org 2x, email@example.com 3x">
To install rehype-resolution with npm, do:
$ npm install rehype-resolution