tooling.report

feature

Compress images

Can images be optimized automatically?

Person in shorts with blue hair walking left

Introduction

It's often useful to be able to "import" images from JavaScript modules, either to obtain a generated asset URL for the image or to inline its contents as a base64-encoded Data URL. Some build tools provide a dedicated "pipeline" for assets like images. In both scenarios, it's important to be able to process the images to minimize their network or bundle size impact.

Tools like Imagemin allow easy automated compression of images without having to specify quality settings or parameters.

The Test

This test builds an application consisting of a JavaScript module that imports an image. Each build tool is configured to apply automated image optimization to image assets, generally using Imagemin.

index.js

import imageUrl from './image.png';
console.log(imageUrl);

image.png

<binary data>

The result should be a JavaScript bundle containing the code from index.js, and an optimized version of image.png. The image size should be reduced compared to its original source version.

Conclusion

browserify

Gulp can be used to process any type of asset, including images. The gulp-imagemin plugin runs image assets through imagemin to optimize them before outputting to the build directory.

parcel

Parcel includes lossless image optimization for PNGs and JPEGs out of the box. It also supports using query parameters when referencing an image to resize or convert images to a different format, or re-encode using a different quality setting.

rollup

Rollup's generateBundle hook gives you full access to build details before files are written. A small plugin can be written to transform the contents of the build.

webpack

Images configured to use the asset module type can be processed using image-webpack-loader or imagemin-webpack-plugin, both of which use Imagemin for optimization. Both solutions can also be applied to images brought into the build via import statements or solutions like copy-webpack-plugin.