Search code examples
reactjswebpackcraco

Craco plugin not loading


I'm trying to add this plugin, which is uses this webpack plugin to my craco config file, followed the guide but it's not working.

const CracoAlias = require('craco-alias');
const imageOptimizer = require('craco-image-optimizer-plugin');
module.exports = function ({ env }) {
  return {
    reactScriptsVersion: 'react-scripts',
    style: {
      postcss: {
        plugins: [
          require('tailwindcss'),
          require('postcss-focus-visible'),
          require('autoprefixer'),
        ],
      },
    },
    plugins: [
      {
        plugin: imageOptimizer,
        // image-webpack-plugin options
        options: {
          mozjpeg: {
            progressive: true,
            quality: 65,
          },
          // optipng.enabled: false will disable optipng
          optipng: {
            enabled: false,
          },
          pngquant: {
            quality: [0.65, 0.9],
            speed: 4,
          },
          gifsicle: {
            interlaced: false,
          },
          // the webp option will enable WEBP
          webp: {
            quality: 75,
          },
        },
      },
      {
        plugin: CracoAlias,
        options: {
          //CracoAlias options
        },
      },
    ],
  };
};

The plugin is supposed to optimize the images, but it's not happening. Any ideas? Is it something wrong with my config file? Thanks.


Solution

  • Seems like it was a problem with react-scripts. Had to add the plugin manually like this:

    const { getLoaders, loaderByName } = require('@craco/craco');
    module.exports = {
      overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions }) => {
        const config = { ...webpackConfig };
        const urlLoaderCandidates = getLoaders(config, loaderByName('url-loader'));
        const urlLoader = urlLoaderCandidates.matches.find(
          m =>
            m.loader &&
            m.loader.test &&
            (Array.isArray(m.loader.test)
              ? m.loader.test.some(r => r.toString().indexOf('jpe?g') >= 0)
              : m.loader.test.toString().indexOf('jpe?g') >= 0)
        );
        if (!urlLoader) {
          throw Error(
            'could not find correct url-loader. did you change react-scripts version?'
          );
        }
        const loader = urlLoader.loader;
        loader.use = [
          {
            loader: loader.loader,
            options: Object.assign({}, loader.options),
          },
          {
            /**
             * @see https://github.com/tcoopman/image-webpack-loader
             */
            loader: 'image-webpack-loader',
            options: pluginOptions,
          },
        ];
        delete loader.loader;
        delete loader.options;
        return config;
      },
    };
    

    And then import the file instead of the package.