Automatically optimizing images in Angular

Dave Ahern
2 min readJan 26, 2020

When deploying images to a production angular environment it is not uncommon to manually attempt to optimize these images using online tools. I find this process to be slow when adding many images. It turns out there is an easier and quicker way to optimize images without having to go through this manual process.

Angular-cli uses webpack under the hood to perform tasks such as bundle optimization. Until now the only way to get at the internal webpack configuration was to use “ng eject”. The problem with using this method is that you are no longer using the angular-cli, a better alternative would be to extend the angular-cli webpack configuration without ejecting it. This is made possible with a plugin called “ngx-build-plus” which can be found here — https://github.com/manfredsteyer/ngx-build-plus.

Webpack itself comes with many great plugins. One in particular for optimizing images is “imagemin-webpack-plugin” which can be found here — https://www.npmjs.com/package/imagemin-webpack-plugin

Run the following commands to install the necessary libraries

// Install the imagemin plugin for webpackyarn add imagemin-webpack-plugin// Install the library to extend angular-cli webpack config. Make sure to use "ng add"ng add ngx-build-plus

Using the “ng add” command will automatically update your angular.json configuration to use the ngx-build-plus tools.

Next, we need to create our webpack config in the root of the project. Create a file called “webpack.partial.js”

var ImageminPlugin = require('imagemin-webpack-plugin').default;module.exports = {    plugins: [        new ImageminPlugin({            pngquant: {                quality: '95-100'            }        })    ]};

Here we are telling webpack to optimize images using the imagemin plugin.

Finally, we need to update the build command in your package.json to use the new webpack partial configuration

{...    "scripts" {    ...        "build": "ng build --prod --extra-webpack-config webpack.partial.js"    ...    }...}

Now when we run the command below and we have images in the assets folder of our application, they will be automatically optimized for us.

yarn build

--

--