首页 > 解决方案 > 带有外部库的 Angular 项目不能使用 angular-cli 在 AOT 模式下编译

问题描述

我开始了一个全新的项目,使用 angular-cli 8.1.2 生成。我想为多个微服务(应用程序)提供一个共享库。这个库不应该包含在应用程序文件夹中,它是一个不同的项目,有自己的 git。如果我尝试这样做,应用程序不会在 aot/production 模式下编译,而是在 jit 下工作。

我想要应用程序的 2 个目录中的 2 个项目:

/test-lib
/test-app

所以我首先用 angular-cli 生成库:

ng new test-lib --create-application=false
(using defaults)
cd test-lib/
ng generate library test-lib --prefix=test
ng build test-lib

这会在 /test-lib/projects/test-lib 中生成库文件夹和项目

现在我生成(第一个)应用程序:

cd ..
ng new test-app
(using defaults)

现在我将 lib 连接到该应用程序:

向 tsconfig.json 添加“路径”:

"paths": {
  "test-lib": [
    "../test-lib/dist/test-lib"
  ],
  "test-lib/*": [
    "../test-lib/dist/test-lib/*"
  ]
}

将导入添加到 app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestLibModule } from 'test-lib';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    TestLibModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

并将这个标签添加到 app.component.html:

<test-test-lib></test-test-lib>

运行“ng serve”现在可以正常工作了。

在文件夹 test-app 中触发“ng build”失败:

ERROR in : Unexpected value 'TestLibModule in C:/Users/.../test-lib/dist/test-lib/test-lib.d.ts' imported by the module 'AppModule in C:/Users/.../test-app/src/app/app.module.ts'. Please add a @NgModule annotation.
enter code here

此外,它报告:

: 'test-test-lib' is not a known element:
1. If 'test-test-lib' is an Angular component, then verify that it is part of this module.
2. If 'test-test-lib' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to 
the '@NgModule.schemas' of this component to suppress this message. ("
</ul>

[ERROR ->]<test-test-lib></test-test-lib>")

我尝试在 app.component.ts 中导入组件也失败了(未找到)

难道不应该以简单的方式使用位于外部文件夹中的 angular-cli 创建一个库吗?

标签: angulartypescriptangular-cli-v7

解决方案


您需要使用库中的 public_api 桶,从中导入模块,然后编译

您也可以使用 npm link 来分隔目录


推荐阅读