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

Posted

技术标签:

【中文标题】在没有 Ivy 的 Angular 10 库中导入 RouterModule【英文标题】:Import RouterModule in Angular 10 Library without Ivy 【发布时间】:2021-05-26 17:12:23 【问题描述】:

我正在构建一个 Angular 10 库以在私有 NPM 存储库上发布。按照 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) 导入要构建的库中?

【问题讨论】:

【参考方案1】:

好吧,经过几个小时的测试和搜索,我找到了与此问题相关的 Angular Issue。

我完全同意@MickL 的最后一条评论;如果这是一个与 View Engine,已经超过 2.5 年没有解决方案了。如果永远无法解决这个问题,只要需要 View Engine 发布库,就应该在Angular documentation 发布官方解决方法。

目前,似乎更简单的解决方法就像在装饰器之前使用常量一样简单,然后在装饰器中使用该值,正如我之前所说的那样;我所缺少的只是export

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

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

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

我真的希望这个问题得到解决,或者至少被 Angular 中的文档所涵盖。

【讨论】:

以上是关于在没有 Ivy 的 Angular 10 库中导入 RouterModule的主要内容,如果未能解决你的问题,请参考以下文章

如何从库中导入组件(在 nrwl/nx 中使用 Angular)

在 Angular 10 中启用 Ivy 的问题

在 Angular2 (TS) 中导入模块的选项

如何在 angular2-webpack 中导入“stompjs/lib/stomp.min”

在使用 WebWorker 时,从导入其他类的文件中导入类会导致 Angular 8 编译失败

在 index.html 中导入 css 和在 Angular 5 中导入 styleUrls 的区别