在没有 Ivy 的 Angular 10 库中导入 RouterModule

问题描述

我正在构建一个要在私有 NPM 存储库上发布的 Angular 10 库。按照 Angular.io 指南,我使用 Angular CLI 使用了 ng new my-workspace --create-application=falseng generate library my-library

我需要为其中一个组件导入 RouterModule,所以我这样做:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MyLibraryComponent } from './my-library.component';

@NgModule({
  declarations: [MyLibraryComponent],imports: [
    RouterModule.forChild(null)
  ],exports: [MyLibraryComponent]
})
export class MyLibraryModule { }

当我尝试构建库时出现此错误:

ERROR: Error during template compile of 'MyLibraryModule'
  Function calls are not supported in decorators but 'RouterModule' was called.

An unhandled exception occurred: Error during template compile of 'MyLibraryModule'
  Function calls are not supported in decorators but 'RouterModule' was called.

See "/tmp/ng-bGhmPt/angular-errors.log" for further details.

我尝试在 const 变量中定义 RouterModule.forChild() 以避免在装饰器中调用函数,但它产生了相同的错误:

import { ModuleWithProviders,NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MyLibraryComponent } from './my-library.component';

const routerModule: ModuleWithProviders<RouterModule> = RouterModule.forChild(null);

@NgModule({
  declarations: [MyLibraryComponent],imports: [routerModule],exports: [MyLibraryComponent],})
export class MyLibraryModule {}

此错误似乎与 Ivy 相关,因为我正在使用 ng build --prod 构建库,而 Ivy 已被禁用用于生产。如果我启用 Ivy,则从 tsconfig.lib.prod.json

中删除此部分
"angularCompilerOptions": {
    "enableIvy": false
}

然后它成功构建,但由于以下错误,我无法将其发布到 NPM:

ERROR: Trying to publish a package that has been compiled by Ivy. This is not allowed.
Please delete and rebuild the package,without compiling with Ivy,before attempting to publish.

我应该如何在没有 Ivy 的情况下在要构建的库中导入 RouterModule (forChild)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)