Angular 12升级后浏览器出现Uncaught TypeError: Cannot read properties of undefined (reading 'ngModule')问题求助
Angular 12升级后自定义库运行时出现
Cannot read properties of undefined (reading 'ngModule')的解决方案 我之前也碰到过一模一样的问题,结合Angular 12的升级特性来看,这个错误基本是因为自定义库的模块导出或导入方式不符合Angular 12的新规范导致的,下面是一步步的解决办法:
1. 修复自定义库中ModuleWithProviders的类型定义
Angular 12开始强制要求ModuleWithProviders必须指定泛型类型(如果你的库模块用了forRoot/forChild这类方法)。打开自定义库中的UtilsModule和PipesModule文件:
旧写法(Angular 11及之前):
export class UtilsModule { static forRoot(): ModuleWithProviders { return { ngModule: UtilsModule, providers: [...] }; } }
新写法(Angular 12+):
import { ModuleWithProviders } from '@angular/core'; export class UtilsModule { static forRoot(): ModuleWithProviders<UtilsModule> { return { ngModule: UtilsModule, providers: [...] }; } }
如果你的模块没有forRoot方法,也要确保@NgModule装饰器的配置没有语法错误(比如漏写括号、导入路径错误等)。
2. 确保自定义库按Angular 12规范构建
升级库的时候,不能只更新package.json里的Angular依赖版本,还要检查库的tsconfig.lib.json配置:
- 确认
target设置为ES2017或更高(Angular 12推荐版本) - 确认
module设置为ES2020或CommonJS(根据库的实际需求选择) - 重新运行库的构建命令:
ng build custom-library,再把构建后的产物更新到你的仓库分支中。
3. 修正主项目对自定义库的导入路径
你当前在tsconfig.json里直接指向了库的源码目录./node_modules/custom-library/src/...,这是错误的——Angular应该导入库编译后的产物,而不是源码。修改tsconfig.json的paths配置:
原错误配置:
{ "paths": { "@pipes/*": ["./node_modules/custom-library/src/pipes/*"], "@utils/*": ["./node_modules/custom-library/src/utils/*"] } }
修正后配置:
{ "paths": { "@pipes/*": ["custom-library/pipes/*"], "@utils/*": ["custom-library/utils/*"] } }
或者更直接的,在AppModule里直接导入库的编译后模块:
import { UtilsModule } from 'custom-library/utils/utils.module'; import { PipesModule } from 'custom-library/pipes/pipes.module';
直接导入源码会导致Angular的编译流程无法正确处理库的模块元数据,运行时自然找不到ngModule的定义。
4. 清理缓存并重新安装依赖
最后,清理所有缓存并重新安装依赖,避免旧的编译产物干扰:
# 清理node_modules和锁文件 rm -rf node_modules rm package-lock.json # 清理npm缓存 npm cache clean --force # 清理Angular缓存 ng cache clean # 重新安装依赖 npm install
完成这些步骤后重新启动项目,应该就能解决浏览器中的ngModule未定义错误了。
内容的提问来源于stack exchange,提问作者Emeka Nwachukwu
相关产品推荐
相关产品推荐

