Serverless部署API触发NormalModuleFactory.beforeResolve报错
Serverless部署Webpack编译报错解决方案
问题表现
执行sls deploy --region $REGION --stage $STAGE部署Serverless API时流程失败,打包阶段抛出16条重复错误,核心报错信息为:
ERROR in NormalModuleFactory.beforeResolve (IgnorePlugin) is no longer a waterfall hook, but a bailing hook instead. Do not return the passed object, but modify it instead. Returning false will ignore the request and results in no module created. webpack 5.73.0 compiled with 16 errors in 38 ms Serverless Error ---------------------------------------- Webpack compilation error, see stats above
已尝试过更新npm与Serverless版本、移除package.json中所有webpack相关依赖排查冲突,均未解决问题。
当前运行环境:
- 操作系统:linux
- Node版本:14.19.1
- Serverless Framework版本:2.72.3(本地安装)
故障原因
webpack 5.7x版本和当前使用的Serverless版本内置的IgnorePlugin钩子逻辑不兼容。
webpack 5.7版本将NormalModuleFactory.beforeResolve从瀑布式钩子调整为保释钩子,旧的插件逻辑仍按照旧规范返回传入的上下文对象,直接触发编译校验错误。之前手动移除项目下webpack依赖不生效,是因为Serverless框架从本地node_modules运行时,会调用自身依赖链路里的webpack包,不受项目根目录直接依赖的影响。
修复方案
按顺序尝试以下方案,绝大多数场景第一个方案就能解决:
- 锁定webpack到兼容版本
在项目根目录执行以下命令,强制将webpack版本锁定到未修改钩子逻辑的稳定兼容版,清理依赖缓存后重装:
重装完成后直接重新执行部署命令即可。npm install webpack@5.68.0 --save-dev --save-exact rm -rf node_modules package-lock.json npm install - 升级serverless-webpack插件到适配版本
如果项目中显式引入了serverless-webpack插件,直接升级到最新稳定版,新版已经适配了webpack 5.7+的钩子逻辑:npm install serverless-webpack@latest --save-dev rm -rf node_modules package-lock.json npm install - 关闭默认webpack打包(无自定义打包需求时用)
如果项目不需要webpack做转译、打包处理,可以直接在serverless.yml中添加配置关闭内置webpack打包逻辑,跳过打包步骤直接部署:custom: webpack: disable: true
内容的提问来源于stack exchange,提问作者Alesio
相关产品推荐
相关产品推荐

