Angular14升级后ngx-build-plus externals失效,构建报错卡顿
升级Angular12至14后ngx-build-plus构建失败的解决方法
问题现象
将Angular项目从12版本升级到14后,执行ng serve --extra-webpack-config webpack.partial.js -o、ng serve或ng build命令时,均出现以下错误,且进程永久卡在打包阶段:
**************************************************************************************** This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION! **************************************************************************************** - Generating browser application bundles (phase: setup)...An unhandled exception occurred: Script file node_modules/rxjs/bundles/rxjs.umd.js does not exist. See "C:\Users\ME\AppData\Local\Temp\ng-LBMvnR\angular-errors.log" for further details. / Generating browser application bundles (phase: setup)...
已确认问题源于ngx-build-plus工具,官方建议添加以下代码,但不清楚具体添加位置及方式:
window.ng.core = require('@angular/core'); window.ng.common = require('@angular/common');
核心问题分析
- UMD bundle文件不存在:Angular14配套的RxJS 7+版本不再提供
umd.js格式的bundle文件,而项目angular.json的scripts配置中仍引用了这类文件,导致构建时找不到路径。 - 官方代码的正确使用方式:官方给出的代码是为了在浏览器环境中暴露Angular核心模块,但不能直接写在webpack配置文件顶层(webpack运行在Node环境,无
window对象)。
分步解决方案
步骤1:移除无效的UMD脚本引用
打开angular.json,找到projects.my-dashboard.architect.build.options.scripts数组,删除所有指向node_modules/*/bundles/*.umd.js的条目,仅保留Web Components相关polyfill:
"scripts": [ { "bundleName": "polyfill-webcomp-es5", "input": "node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js" }, { "bundleName": "polyfill-webcomp", "input": "node_modules/@webcomponents/webcomponentsjs/bundles/webcomponents-sd-ce-pf.js" }, "node_modules/@webcomponents/custom-elements/src/native-shim.js" ]
步骤2:正确添加官方建议的代码
方案A:通过自定义shim文件注入
- 在项目
src目录下创建ng-shim.js文件,内容如下:
window.ng = window.ng || {}; window.ng.core = require('@angular/core'); window.ng.common = require('@angular/common');
- 将该文件添加到
angular.json的scripts数组末尾:
"scripts": [ // ... 已保留的Web Components polyfill "src/ng-shim.js" ]
方案B:通过webpack配置插件实现
修改webpack.externals.js,使用webpack的ProvidePlugin在全局暴露模块,避免直接操作window:
const webpack = require('webpack'); module.exports = { plugins: [ new webpack.ProvidePlugin({ 'ng.core': '@angular/core', 'ng.common': '@angular/common' }) ], externals: {} };
构建时指定该配置:ng build --extra-webpack-config webpack.externals.js --prod --single-bundle
步骤3:验证修复
执行ng serve或ng build命令,确认错误消失,打包流程正常完成。
内容的提问来源于stack exchange,提问作者Boommeister
相关产品推荐
相关产品推荐

