Parcel 2: HTML Image Transformer
See original GitHub issueCreate the @parcel/transformer-html-images
(name TBD) package. This should include a Transformer plugin that transforms <img>
tags in HTML to <picture>
elements with multiple sources. It should work with the @parcel/transformer-webp and @parcel/transformer-image-resize plugins to create multiple dependencies that are transformed by those plugins and re-inserted later as URLs. This handles generating multiple versions of an image with different sizes and formats from a source HTML file and image completely automatically.
HTML like this:
<img src="./image.jpg" width="200">
should be transformed into HTML like this, with dependencies created for each referenced asset:
<picture>
<source type="image/webp" srcset="webp:./image.jpg?width=200, webp:./image.jpg?width=400 2x">
<source type="image/jpeg" srcset="./image.jpg?width=200, ./image.jpg?width=400 2x">
<img src="./image.jpg?width=200" width="200">
</picture>
This automatically handles creating both WebP and JPG versions of the image, at multiple resolutions.
In addition, the srcset
attribute should be supported to generate multiple versions with specific sizes from the same input image:
<img srcset="image.jpg 480w, image.jpg 1080w">
becomes:
<picture>
<source type="image/webp" srcset="webp:image.jpg?width=480 480w, webp:image.jpg?width=1080 1080w">
<source type="image/jpeg" srcset="image.jpg?width=480 480w image.jpg?width=1080 1080w">
<img src="./image.jpg?width=1080w">
</picture>
Note that the protocol and query param syntax here is internal to Parcel and would not be shipped to users. After the images are transformed, the final URL would be placed into the HTML file as expected.
Open Questions
- What should the default resolutions include? 1x, 2x, 3x? Should this happen by default at all or should we require users specify
srcset
in their code themselves? Seems like it should be fairly common to want this… - What should the default formats include? WebP and the original format? WebP and JPEG always?
- What should happen if there is no
width
orheight
set on an<img>
? Just convert to WebP without resizing?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:7 (5 by maintainers)
I wouldn’t want this to be specific to HTML. I have a lot of my source images as SVG but sometimes need/want them rendered into other formats. For example:
All of these would have a use for images rendered into select formats at different resolutions. Can we try to find a solution that works uniformly wherever images are needed?
1x
and2x
is probably enough as a default (though I have found2x
images can still be fairly large and1.5x
can be a decent compromise).Reading https://www.smashingmagazine.com/2021/09/modern-image-formats-avif-webp/ and https://www.contentful.com/blog/2021/11/29/load-avif-webp-using-html/, I wonder if it should be like:
There’s never going to be a silver bullet for this though.