在本地项目中使用 Angular 库组件 - 不工作

分享于2022年07月17日 angular 问答
【问题标题】:在本地项目中使用 Angular 库组件 - 不工作(Using Angular Library component in local project - not working)
【发布时间】:2022-01-23 12:17:17
【问题描述】:

我创建了一个包含我的项目和库的 Angular 工作区。 下面是项目结构:

Using Angular Library component in local project - not working

我已经建立了我的库 -(这使用表单模块)

ng build demo-lib

它编译成功并在 dist 文件夹中创建一个文件夹。

现在我已经在 app.module.ts 中导入了模块并在 import 下添加:

import { DemoFormComponent, DemoLibModule } from 'demo-lib'
.
.
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DemoLibModule,
    DemoFormComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

但是当我为我的应用程序提供服务时,我得到了以下错误,我不确定我做错了什么:-

Error: dist/demo-lib/lib/demo-form/demo-form.component.d.ts:4: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 (demo-lib) which declares DemoFormComponent has not been processed correctly by ngcc.

4 export declare class DemoFormComponent implements OnInit {
                       ~~~~~~~~~~~~~~~~~

谁能帮我解决这个问题?

  • 哪个版本的 Angular?
  • 可能与从 View Engine to Ivy 搬家有关。
  • 不知道这个 SO 是否相关
  • --Angular CLI: 13.1.2
  • @rveerd 我正在 Angular 13 创建一个新库,不知道为什么它应该使用视图引擎...我们需要设置常春藤还是默认设置,我不确定我在某处读过从 Angular 12 开始,常春藤是默认的?

【解决方案1】:

您只能将模块导入到您的模块中。您不能(也不需要)导入组件。

您的库模块导出组件。当您在应用程序中使用该组件时,这足以让 Angular 找到该组件。

import { DemoLibModule } from 'demo-lib'
.
.
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    DemoLibModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

  • 非常感谢您删除了这个有用的东西......真是个愚蠢的错误,我为此浪费了一整天。