Image

Parcel has built in support for resizing, converting, and optimizing images. Images can be referenced from HTML, CSS, JavaScript, or any other file type.

Resizing and converting images

#

Parcel includes an image transformer out of the box, which allows you to resize images, convert them to a different format, or adjust the quality to reduce file size. This can be done using query parameters when referencing the image.

Images are resized and converted in production builds, or when the --optimize flag is used. In development, the original image is used as is, which keeps builds fast.

The query parameters you can use are:

Image formats

#

The following image formats are supported, both as input and as output via the as query parameter:

AVIF is also supported as an output format, but not as an input:

The following formats are also supported as inputs, but are not generally supported by browsers: tiff and bmp. These must be converted to another format using the as query parameter.

For more guidance on choosing the right image formats, see the guide on web.dev.

JavaScript

#

To reference an image from JavaScript, use the URL constructor. For more details, see URL dependencies in the JavaScript docs.

main.js:
const imageUrl = new URL("image.jpeg?as=webp&width=250", import.meta.url);

HTML

#

To reference an image from HTML, use the <img> or <picture> element. The same image can be referenced multiple times with different query parameters to create multiple versions in different formats or sizes. See the HTML docs for more details.

index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML Example</title>
</head>
<body>
<picture>
<source srcset="image.jpeg?as=avif&width=800" type="image/avif" />
<source srcset="image.jpeg?as=webp&width=800" type="image/webp" />
<source srcset="image.jpeg?width=800" type="image/jpeg" />
<img src="image.jpeg?width=200" alt="test image" />
</picture>
</body>
</html>

Image optimization

#

Parcel also includes lossless image optimization for JPEGs and PNGs by default in production mode, which reduces the size of images without affecting their quality. This does not require any query parameters or configuration to use. However, since the optimization is lossless, the size reduction possible may be less than if you use the quality query param, or use a modern format such as WebP or AVIF.

Disabling image optimization

#

To disable the default image optimization for JPEGs and PNGs in production mode, replace the image transformer for these files with @parcel/transformer-raw in your .parcelrc configuration file. Note that this also disables resizing and converting these images with query parameters.

.parcelrc:
{
"extends": "@parcel/config-default",
"transformers": {
"*.{jpg,jpeg,png}": ["@parcel/transformer-raw"]
}
}