首页 > 解决方案 > 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

标签: webpackwebpack-4webpack-5

解决方案


我想你可以跟进official document然后它会正常工作。

顺便说一句,您的代码应该可能更改为:

{
  // ...
  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.');
          }
        });
      } 
    }
  ]
}

推荐阅读