Skip to content

Transforming Markdown Images

PicPerf’s Rehype and Remark plugins make it easy to transform and optimize images in Markdown.

Rehype Plugin

Use the PicPerf Rehype plugin to easily transform and optimize Markdown images after they’ve been transformed to HTML.

Installing the Rehype Plugin

Run npm install @picperf/rehype.

Usage

Wire it up by importing the plugin and configuring it with your Markdown setup. Here’s an example from Astro:

import { rehypePicPerf } from "@picperf/rehype";
export default defineConfig({
markdown: {
rehypePlugins: [rehypePicPerf],
},
// Other stuff...
});

Disabling Transformations

By default, absolute URLs will be prefixed with “https://picperf.io”. If you’d like to disable this behavior for particular URLs, you can use the shouldTransform() option, which should return a boolean. If true, the URL will be transformed (assuming it’s absolute — see more on that below). If false, the URL will be left alone.

markdown:{
rehypePlugins: [[ rehypePicPerf, {
shouldTransform: (url) => {
// Return a boolean based on the URL, or not.
return false;
}
}]],
},

Transforming Root-Relative URLs

Out of the box, this plugin will not transform image root-relative URLs, like this:

![my image](/my-image.jpg)

In order to transform these, pass a host option. This value will be used alongside the PicPerf host to transform the URL.

markdown:{
rehypePlugins: [[ rehypePicPerf, {
host: "https://macarthur.me"
}]],
},

Remark Plugin

PicPerf’s Remark plugin is another approach to transforming your Markdown images, particularly before they’ve been transformed into HTML.

Installing the Remark Plugin

Run npm install @picperf/remark.

Usage

Import the plugin and configure it. If you’re using Astro, it’d look something like this:

import { remarkPicPerf } from "@picperf/remark";
export default defineConfig({
markdown: {
remarkPlugins: [remarkPicPerf],
},
// Other stuff...
});

Disabling Transformations

Out of the box, URLs will be prefixed with “https://picperf.io”. This behavior can be disabled for particular URLs using the shouldTransform() option — a function that should return a boolean. If true, absolute URLs will be transformed. If false, the URLs will be left unchanged.

markdown:{
remarkPlugins: [[ remarkPicPerf, {
shouldTransform: (url) => {
// Return a boolean based on the URL, or not.
return false;
}
}]],
},

Transforming Root-Relative URLs

By default, the Remark plugin will not mess with images using root-relative URLs, like this:

![my image](/my-image.jpg)

If you’d like to transform these, pass a host option. The provided value will be used to then transform the URL.

markdown:{
rehypePlugins: [[ rehypePicPerf, {
host: "https://macarthur.me"
}]],
},