升级Webpack至5.88后CopyWebpackPlugin及HtmlWebpackPlugin报错求助
问题1:CopyWebpackPlugin配置格式不兼容
升级Webpack从4.43到5.88后,执行yarn build出现以下错误:
YN0000: [..]: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
➤ YN0000: [..]: - options[0] has an unknown property 'to'. These properties are valid:
➤ YN0000: [..]: object { patterns, options? }
➤ YN0000: [..]: ValidationError: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
原Webpack配置(webpack.config.babel.js第86行):
plugins: [ .. new CopyWebpackPlugin([ { from: 'src/data', to: 'data' }, { from: 'src/images', to: 'images' } ]), .. ]
解决办法
Webpack 5对应的CopyWebpackPlugin版本已更新配置格式,需将数组形式的参数改为包含patterns字段的对象:
plugins: [ .. new CopyWebpackPlugin({ patterns: [ { from: 'src/data', to: 'data' }, { from: 'src/images', to: 'images' } ] }), .. ]
问题2:HtmlWebpackPlugin兼容错误
修改CopyWebpackPlugin配置后,出现新错误:
YN0000: [..]: TypeError: Cannot read properties of undefined (reading 'tap')
➤ YN0000: [..]: at HtmlWebpackPlugin.apply (%app%\node_modules\html-webpack-plugin\index.js:40:31)
当前使用的webpack-cli版本为"webpack-cli": "^5.1.4"。
解决办法
该错误因HtmlWebpackPlugin版本过低,不兼容Webpack 5导致,需升级至支持Webpack 5的版本:
- 执行升级命令:
yarn add html-webpack-plugin@latest --dev
或
npm install html-webpack-plugin@latest --save-dev
- 当前
webpack-cli@5.1.4与Webpack 5兼容,无需调整。
内容的提问来源于stack exchange,提问作者Unnamed

