Webpack 5.84.0+ 出现flatMap is not a function错误,如何解决?
Webpack最新版本构建报错问题解决
我在学习Webpack教程时,刚尝试编译就遇到错误。安装Webpack和webpack-cli后,执行构建脚本出现以下报错:
[webpack-cli] TypeError: ["webpack.config",".webpack/webpack.config",".webpack/webpackfile"].flatMap is not a function at WebpackCLI.loadConfig (C:\Users\xxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\lib\webpack-cli.js:1439:15) at WebpackCLI.createCompiler (C:\Users\xxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\lib\webpack-cli.js:1714:33) at WebpackCLI.runWebpack (C:\Users\xxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\lib\webpack-cli.js:1810:31) at Command.makeCommand (C:\Users\xxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\lib\webpack-cli.js:892:32) at Command.listener [as _actionHandler] (C:\Users\xxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:482:17) at actionResult._chainOrCall (C:\Users\xxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:1283:65) at Command._chainOrCall (C:\Users\xxxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:1177:12) at Command._parseCommand (C:\Users\xxxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:1283:27) at hookResult._chainOrCall (C:\Users\xxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:1081:27) at Command._chainOrCall (C:\Users\xxxxxxxxxxx\Documents\Repositories\webpack-starter\node_modules\webpack-cli\node_modules\commander\lib\command.js:1177:12) npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! webpack-starter@1.0.0 build: `webpack --mode production` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the webpack-starter@1.0.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\xxxxxxxx\AppData\Roaming\npm-cache\_logs\2023-05-26T14_49_54_605Z-debug.log
将Webpack从5.84.0降级到5.70.0、webpack-cli从5.0.1降级到4.9.2后错误消失。请问能否使用最新版本完成简单npm构建,还是这是无法修复的破坏性变更?
问题原因与解决方案
这个报错的核心原因是Node.js版本过低:Array.flatMap()是Node.js 11及以上才支持的API,你当前使用的Node.js版本不兼容该方法,导致webpack-cli代码执行失败。
完全可以使用最新版本的Webpack和webpack-cli完成构建,无需降级,只需执行以下步骤:
- 升级Node.js版本到16.x及以上(Webpack 5官方推荐最低版本为10.13.0,但webpack-cli 5.x对Node.js版本要求更高,建议直接安装最新LTS版本)
- 升级后清理旧依赖并重新安装:
- 删除项目根目录下的
node_modules文件夹和package-lock.json文件 - 执行
npm install重新安装依赖 - 再次运行构建命令
npm run build
- 删除项目根目录下的
这并非Webpack的破坏性变更,只是新版本webpack-cli依赖了更高版本Node.js的原生API,升级Node.js即可正常使用最新版Webpack套件。
内容的提问来源于stack exchange,提问作者Robert Carmichael
相关产品推荐
相关产品推荐

