How to compress images with ImageMinimizerWebpackPlugin in Next.js (webpack 5)?

Viewed 994

I want to compress images using this plugin, but I am faced with the problem that the build goes through, but the images are not compressed.

I'm new to webpack and don't understand what is wrong (maybe I need an exit point for compressed files as a folder?)

next.config.js

const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");

const nextConfig = {
  future: {
    webpack5: true
  },

  webpack: (config, options) => {

    config.module.rules.push({
      test: /\.(jpe?g|png|svg)$/i,
      type: "asset",
    })

    config.plugins.push(new ImageMinimizerPlugin({
      minimizerOptions: {
        // Lossless optimization with custom option
        // Feel free to experiment with options for better result for you
        plugins: [
          ["jpegtran", { progressive: true }],
          ["optipng", { optimizationLevel: 5 }],
          // Svgo configuration here https://github.com/svg/svgo#configuration
          [
            "svgo",
              {
                plugins: 
                  {
                    name: "removeViewBox",
                    active: false,
                  },
              },
            ],
          ],
        },
      })
    )
    return config
  },
};

module.exports = nextConfig
1 Answers

Had the same issue and couldn't fix it with imagemin. The only thing that worked is when I switched to using squoosh as described in the Plugin docs.

If you want to use imagemin, the only solution I can recommend at the moment is to use image-webpack-loader instead of the new asset feature of Webpack 5.

Related