Search code examples
webpackwebpack-4webpack-5

Convert inline plugin webpack 4 to webpack 5


For my project, I was using webpack 4 with Karma to run my test. Everything was working fine. And I successfully migrate to webpack 5.

However, I had a custom inline plugin that I found on GitHub and I don't know how to convert it to make it work on webpack 5.

webpack.config

// ...
plugins: [
    // ...
    function()
    {
        this.plugin("done", function(stats)
        {
            if (stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1)
            {
                console.log(stats.compilation.errors);
                process.exit(1); // or throw new Error('webpack build failed.');
            }
            // ...
        });
    }
    // ...
],
// ...

Indeed, I have this error on webpack 5:

09 03 2021 01:56:20.991:ERROR [karma-server]: Error during file loading or preprocessing

TypeError: this.plugin is not a function


Solution

  • I think you can follow up the official document then it would work normally.

    BTW, your code should potentially be changed to:

    {
      // ...
      plugins: [
        new class YourPlugin {
          apply(compiler) {
            compiler.hooks.done.tap('YourPlugin', (
              stats
            ) => {
              if (
                stats.compilation.errors && 
                stats.compilation.errors.length && process.argv.indexOf('--watch') == -1
              ) {
                console.log(stats.compilation.errors);
                process.exit(1); // or throw new Error('webpack build failed.');
              }
            });
          } 
        }
      ]
    }