Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import { visit } from 'unist-util-visit';
export default function rehypePictureImages() {
return (tree) => {
visit(tree, 'element', (node, index, parent) => {
if (node.tagName !== 'img') return;
const src = node.properties?.src;
if (!src) return;
// Only process local blog images (not GIFs)
if (!src.startsWith('/images/blog/') || src.endsWith('.gif')) return;
// Generate WebP URL
const webpSrc = src.replace(/\.(png|jpe?g)$/i, '.webp');
// Create <picture> element wrapping the <img>
const pictureNode = {
type: 'element',
tagName: 'picture',
properties: {},
children: [
{
type: 'element',
tagName: 'source',
properties: {
srcSet: webpSrc,
type: 'image/webp',
},
children: [],
},
node, // the original <img>
],
};
// Replace the <img> with <picture> in the parent
if (parent && typeof index === 'number') {
parent.children[index] = pictureNode;
}
});
};
}
|