You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级至Angular@15后出现'SharedModule非NgModule类'编译错误

Angular 13升级到15后SharedModule编译错误排查与解决

问题现象

升级完成后出现编译错误:

'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规范。

修复步骤:

  1. 修改LoadingIndicatorModule中forRoot方法的返回类型,将ModuleWithProviders<any>替换为ModuleWithProviders<LoadingIndicatorModule>:
static forRoot(config?: LukanaLoadingModuleConfig): ModuleWithProviders<LoadingIndicatorModule> {
  return {
    ngModule: LoadingIndicatorModule,
    providers: [
      {
        provide: CONFIG,
        useValue: config
      },
    ]
  };
}
  1. 重新编译项目,错误即可消除。

内容的提问来源于stack exchange,提问作者piernik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:55:23