Automating Image Optimization During Build Time

Create a script that runs during the Next.js build process to optimize all static images using an image optimization library before deployment.
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
const imageminGifsicle = require('imagemin-gifsicle');
const imageminSvgo = require('imagemin-svgo');

(async () => {
    const files = await imagemin(['public/images/*.{jpg,png,gif,svg}'], {
        destination: 'public/images/',
        plugins: [
            imageminMozjpeg({ quality: 75 }),
                quality: [0.6, 0.8]
                plugins: [
                    { removeViewBox: false }

    console.log('Images optimized', files);
This script uses the 'imagemin' library and respective plugins to optimize JPG, PNG, GIF, and SVG images located in the 'public/images' directory. The optimized images are overwritten in the same directory. We use various plugins to ensure each image format is optimally compressed. 'async' function ensures asynchronous execution of the image optimization process.
const fs = require('fs');
const path = require('path');

exports.optimizeImages = async () => {
    if (process.env.NODE_ENV !== 'production') {
        console.log('Skipping image optimization in development mode.');

    // Add your image optimization logic here
    // Example: await optimizeJPGs(); await optimizePNGs();

if (require.main === module) {
    (async () => {
        try {
            await exports.optimizeImages();
            console.log('Image optimization complete.');
        } catch (err) {
            console.error('Error during image optimization', err);
This is a module that exposes an asynchronous function called 'optimizeImages', which runs the image optimization process only when in production mode. It has a condition to prevent it from running during development. The module can also be executed directly via command line, but if any errors occur, the process will exit with an error code 1.
// This example assumes you have a 'postbuild' script in your 'package.json'
// Add the following to your 'package.json' scripts section:
// "scripts": {
//   "build": "next build",
//   "postbuild": "node image-optimization.js",
//   ...
// }
This is an instruction snippet to be added in the 'package.json' file under the 'scripts' section. It demonstrates how to run the image optimization script automatically after the Next.js build process by using a 'postbuild' script, which is executed immediately after the 'build' script.