【问题标题】:Angular project with external lib doesn't compile in AOT mode using angular-cli带有外部库的 Angular 项目不能使用 angular-cli 在 AOT 模式下编译
【发布时间】:2019-07-22 07:32:21
【问题描述】:

我开始了一个全新的项目,使用 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 库吗?

【问题讨论】:

    标签: angular typescript angular-cli-v7


    【解决方案1】:

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

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

    【讨论】:

    • 我以为我已经这样做了。如果我使用 import { TestLibModule } from 'test-lib/public-api';在我的 app.module.ts 中,我得到了相同的结果。我将 export * 更改为 export { TestLibModule } from './lib/test-lib.module';在 public-api.ts 中,但这也没有帮助。
    • 请发布您的TestLib模块
    • 我认为您的 tsconfig 路径存在问题,因为它们指向 dist,请尝试像这样导入您的库: import {//your imports} from '../../projects/ testLib/src/public_api'
    • 好的,我现在也上传了测试应用程序:github.com/cgaeking/test-app 我尝试 import { TestLibModule } from '../../../test-lib/projects/test-lib/ src/public-api';但同样的错误出现了
    • 你的导入是错误的 import { TestLibModule } from '../../projects/test-lib/src/public-api'。您的项目目录必须与 src 目录处于同一级别
    猜你喜欢
    • 2017-03-28
    • 2018-02-14
    • 2018-02-27
    • 2018-12-13
    • 2019-08-02
    • 2017-10-22
    • 2018-09-09
    • 2017-02-24
    • 2018-08-29
    相关资源
    最近更新 更多