首页 > 解决方案 > Webpack 从 V4 更新到 V5:this.plugin 不是函数

问题描述

这是我的 webpack 的 package.json 版本:

"webpack": "5.25.0",
"webpack-cli": "4.5.0",
"webpack-merge": "5.7.3"

所以最新版本的所有人。我来自 4.31 的 webpack 版本。

在我的 webpack.production.js 的 plugins 数组中,我有:

        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[hash].app.css',
        }),
        function symfonyAssetsVersion() {
            this.plugin('done', (stats) => {
                fs.writeFile(
                    path.join(__dirname, 'config/packages/', 'assets_version.yaml'),
                    `parameters:\n    assets_hash: ${stats.hash}\n`,
                    (err) => { if (err) throw err; }
                );
            });
        },
    ],

My CircleCi tool tells that:


[webpack-cli] TypeError: this.plugin is not a function
    at Compiler.symfonyAssetsVersion (/app/webpack.production.js:27:18)
    at createCompiler (/app/node_modules/webpack/lib/webpack.js:69:12)
    at create (/app/node_modules/webpack/lib/webpack.js:118:16)
    at webpack (/app/node_modules/webpack/lib/webpack.js:126:47)
    at WebpackCLI.f [as webpack] (/app/node_modules/webpack/lib/index.js:41:15)
    at WebpackCLI.createCompiler (/app/node_modules/webpack-cli/lib/webpack-cli.js:1678:29)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) ```

Any idea on how to fix the this.plugin is not a function ? 

Thank you

标签: webpackmigration

解决方案


您必须重写symfonyAssetsVersion()为与 Webpack 5 的 api 匹配的自定义插件。您可以在此处阅读更多信息:https ://webpack.js.org/contribute/writing-a-plugin/ 。

基本上,在原型上使用 apply 创建一个新类。然后挂钩compiler.hooks.done,回调中会提供统计信息。


推荐阅读