statsByDimensionsSync generates wrong src on first run #146
Description
I'm using sanity studio and their portable text with a serializer, to turn the portable text into html.
The serializer is a shortcode, that looks like this:
const { toHTML } = require('@portabletext/to-html');
const generateImage = require('./image');
const blocks = {
types: {
imageWithCaption: ({ value: { image } }) => {
const {
width,
height
} = image.asset.metadata.dimensions;
const imageHTML = generateImage({
src: image.asset.url,
alt: image.alt,
sizes: "(min-width: 732px) 80ch, 100vw",
width,
height
});
return imageHTML;
}
}
}
module.exports = function renderHTML(input) {
return toHTML(input, { components: blocks });
}
And the generateImage()
function is:
const Image = require('@11ty/eleventy-img');
module.exports = function imageSyncShortcode(props) {
const {
src,
width,
height,
alt,
sizes,
loading,
decoding
} = props;
const image_attributes = {
alt,
sizes,
loading: loading ?? 'lazy',
decoding: decoding ?? 'async',
}
const options = {
widths: [320, 400, 700, 1200, 2000],
formats: ['avif', 'webp', 'jpeg'],
urlPath: '/images/',
outputDir: './dist/images/'
}
Image(src, options);
let metadata = Image.statsByDimensionsSync(src, width, height, options);
return Image.generateHTML(metadata, image_attributes);
}
I'm using Image.statsByDimensionsSync()
so that I don`t have to use async – I tried the async way before, but that didn't work in conjunction with the sanity serializer.
I found that Image.statsByDimensionsSync()
generates a different src
on the first run. So when I just build the site, the generated html for the image tries to load a file that doesn't exist. When I use eleventy serve and let eleventy rebuild the site once, it works fine.
I assume that eleventy generates the filename based on a different value on the first run than on subsequent runs.
E.g. on the first run the src is /images/CWhDmUxMUw-320.jpeg
, on subsequent runs it's /images/Zzo8VdfzGM-320.jpeg