【问题标题】:Using Angular library in the application causes error在应用程序中使用 Angular 库会导致错误
【发布时间】:2021-11-24 03:27:47
【问题描述】:

我有一个名为“test”的简单 Angular 库项目,其中只有一个组件显示材质图标。我已经构建了它(ng build test)

我的库模块:

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
  ],
  exports: [
    TestComponent
  ]
})
export class TestModule { }

我想在我的 Angular 应用程序中测试这个库。我在 app.module.ts 中添加了库:

import {TestComponent} from '../../dist/test'

@NgModule({
  imports: [
    TestComponent,

我正在使用这个组件,但不幸的是我在 ng serve 命令期间遇到了错误:

Error: ../../dist/test/lib/test.component.d.ts:3:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the dependency which declares TestComponent has not been processed correctly by ngcc.

【问题讨论】:

  • 您应该将 TestModule 导入 AppModule,而不是 TestComponent

标签: angular angular-library angular12


【解决方案1】:

您应该将 TestModule 导入 AppModule,而不是 TestComponent

【讨论】:

    【解决方案2】:

    正确的做法是在你的库中定义一个 Angular TestModule 并让它在其声明数组中包含 TestComponent。然后,您可以将该模块导入您的AppModule

    否则,您必须将TestComponent 直接包含在AppModule declarations 中,这超出了拥有库的目的。

    【讨论】:

    • 我的图书馆和你说的一模一样。我修改了我的帖子,以便您可以看到我的库模块的样子。
    • @Ellbar 库应该“声明”和“导出”组件。如果您使用ng g module ...ng g module ... 创建它们,它会正确创建它们。
    • 我通过 Angular CLI 创建了库,没有手动创建任何内容。 TestComponent 和 TestModule 是 ng generate library test 创建的默认组件和模块
    • @Ellbar 问题是您在AppModule 中导入TestComponent 而不是TestModule
    猜你喜欢
    • 2021-04-29
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多