升级至Angular@15后出现'SharedModule非NgModule类'编译错误
问题现象
升级完成后出现编译错误:
'SharedModule' does not appear to be an NgModule class.
src/app/shared/shared.module.ts:127:14
127 export class SharedModule {
~~~~~~~~~~~~
Is it missing an @NgModule annotation?
确认SharedModule已添加@NgModule注解,且定位到错误由LoadingIndicatorModule.forRoot({})的引入触发。
SharedModule核心代码
import {NgModule} from '@angular/core'; // 其余导入语句省略 import {LoadingIndicatorModule} from '@lukana/loading-indicator'; @NgModule({ imports: [ // 其余导入模块省略 LoadingIndicatorModule.forRoot({}), // 问题触发点 // 其余导入模块省略 ], declarations: [ BlankPageComponent, PageEmptyRouterOutletComponent, DropdownComponent, StickyDirective, ClickStopPropagationDirective, ], exports: [ // 其余导出内容省略 LoadingIndicatorModule, // 其余导出内容省略 ] }) export class SharedModule { }
LoadingIndicatorModule源码
import {ModuleWithProviders, NgModule} from '@angular/core'; import {LoadingOverlayDirective} from './loading-overlay.directive'; import {LoadingBarDirective} from './loading-bar.directive'; import {LukanaLoadingModuleConfig} from './models/lukana-loading-module-config'; import {CONFIG} from './configToken'; @NgModule({ imports: [], declarations: [LoadingOverlayDirective, LoadingBarDirective], exports: [LoadingOverlayDirective, LoadingBarDirective] }) export class LoadingIndicatorModule { static forRoot(config?: LukanaLoadingModuleConfig): ModuleWithProviders<any> { return { ngModule: LoadingIndicatorModule, providers: [ { provide: CONFIG, useValue: config }, ] }; } }
问题原因与解决方法
Angular 14+ 对ModuleWithProviders的类型检查做了严格升级,不再允许使用ModuleWithProviders<any>这种模糊的泛型声明,必须指定对应模块的具体类型,否则编译器无法正确识别模块元数据,进而误判上层的SharedModule不符合NgModule规范。
修复步骤:
- 修改
LoadingIndicatorModule中forRoot方法的返回类型,将ModuleWithProviders<any>替换为ModuleWithProviders<LoadingIndicatorModule>:
static forRoot(config?: LukanaLoadingModuleConfig): ModuleWithProviders<LoadingIndicatorModule> { return { ngModule: LoadingIndicatorModule, providers: [ { provide: CONFIG, useValue: config }, ] }; }
- 重新编译项目,错误即可消除。
内容的提问来源于stack exchange,提问作者piernik
相关产品推荐
相关产品推荐

