Angular Workspace/Monorepo,forRoot 给我错误。 "A value for 'forRoot' cannot be determined statically, as it is an external declaration."

Angular Workspace/Monorepo, forRoot giving me errors. "A value for 'forRoot' cannot be determined statically, as it is an external declaration."

我有一个名为 Themex 的图书馆。

//envInjector.ts
    import {InjectionToken} from "@angular/core";
    export const ENVIRONMENT = new InjectionToken<{[key: string]: any}>('ENVIRONMENT');

//themex.module.ts

import {ENVIRONMENT} from "./envInjector";
 
    
    @NgModule({
      declarations: [
    ThemexComponent,
    ModalComponent,
    UploadComponent,
    AlertComponent,

  ],
  imports: [
    CommonModule
  ],
  exports: [
    ThemexComponent,
    ModalComponent,
    UploadComponent,
    AlertComponent,
  ],
  providers: []
})

export class ThemexModule {
  static forRoot(config: {[key: string]: any}): ModuleWithProviders<any> {
    return {
      ngModule: ThemexModule,
      providers: [
        {
          provide: ENVIRONMENT,
          useValue: config
        }
      ]
    };
  }

}

库被导入到同一 angular 工作区内的 angular 项目中。

import {ThemexModule} from "themex";

如果我按照上面给出的方式导入它,我会收到错误消息。

“'forRoot' 的值无法静态确定,因为它是外部声明。 “

但是,如果我按如下所示导入它,一切似乎都有效。

import {ThemexModule} from "../../../themex/src/lib/themex.module";

我正在使用

Angular CLI: 12.0.5
Node: 14.16.1

我的编译器选项。 tsConfig.json

所有的错误都是在我做 ng serve 时出现的。我还没有尝试构建。

最近几天我遇到了这个问题,我想我已经找到了解决方案。对我来说,它发生在我从 Angular 10.

升级我们的一些库的依赖项时

我们的解决方案是确保 ModuleWithProviders return 类型是模块的强类型,因此在您的情况下:

export class ThemexModule {
  static forRoot(config: {[key: string]: any}): ModuleWithProviders<ThemexModule> {
    [...]
}

正确!提供签名是 must 特别是 if/when Ivy 标志是打开的、完整的或部分的。

如果您没有 forRoot()forChild(),则无需担心 ModuleWithProviders。如果你这样做,那么 return 类型。

这是在将可发布的库推送到 npm 而其他人将其拉入时使用的。

export class SomeModuleModule {
  static forRoot(...): ModuleWithProviders<SomeModuleModule> {...}
}
{
  "angularCompilerOptions": {
    "enableIvy": true,
    "compilationMode": "partial"
  }
}