如何处理 Angular 库次要条目之间的依赖关系

How to handle dependencies between Angular Library secondary entries

我正在尝试将 Angular 应用程序中的现有代码构建到共享库中。该库也应该被其他应用程序使用。因此,我创建了多个子条目来构建可摇树的代码。

考虑以下结构:


- lib
  - entryA
      - /src
      - index.ts
      - public-api.ts
      - package.json
  - entryB
      - /src
      - index.ts
      - public-api.ts
      - package.json
  - entryC
      - /src
      - index.ts
      - public-api.ts
      - package.json
  - ...
- ng-package.json
- package.json

一些条目依赖于其他条目(没有循环依赖)。例如 EntryA 没有依赖项,但 EntryB 依赖于 EntryA,因此在 EntryB.

中导入

然后在EntryB中导入特定服务:

import { MyService } from '@myorg/mylib/lib/entryA';

路径由tsconfig.json文件中的配置解析:

"paths": {
  "@myorg/mylib/*": ["./projects/ui/*", "./projects/ui"],
  "@myorg/mylib": ["./dist/ui/*", "./dist/ui"],
}

库的构建按预期工作并且没有抛出任何错误。在消费者应用程序中,库是通过 package.json 定义的,并导入到 angular 模块中。应用程序想要使用 EntryB:

import { MyModule } from '@myorg/mylib/lib/entryB';

然而,消费者应用程序的构建抛出错误,它无法在 EntryB 中找到 EntryA 所需的依赖项:

ERROR in The target entry-point "@myorg/mylib/lib/entryB" has missing dependencies:
 - @myorg/mylib/lib/entryA

如何处理这些子条目之间的依赖关系?

- lib
  - entryA
      - /src
      - index.ts
      - public-api.ts
      - package.json

      - entryB
         - /src
         - index.ts
         - public-api.ts
         - package.json

- ng-package.json
- package.json


import { entryA } from "../../entryA/src/app/app.module";

我找到了解决方案,因此回答了我自己的问题:

问题是由于不同的编译。在Angular10,Ivy可用于应用。但是这个库不是用 Ivy 编译的,不应该在 npm 存储库中用 Ivy 发布。由于依赖关系,无法完成对 Angular 10 的更新以启用 partial 编译。

There are three distribution formats that you can use when publishing a library:

View Engine (deprecated)—legacy format, slated for removal in Angular version 13. Only use this format if you must support View Engine applications. partial-Ivy (recommended)—contains portable code that can be consumed by Ivy applications built with any version of Angular from v12 onwards. full-Ivy—contains private Angular Ivy instructions, which are not guaranteed to work across different versions of Angular. This format requires that the library and application are built with the exact same version of Angular. This format is useful for environments where all library and application code is built directly from source.

参见:https://angular.io/guide/creating-libraries#ensuring-library-version-compatibility

我有,因为这是一个私人 npm 包,因此将 tsconfig.lib.prod.json 中的构建选项 enableIvy 设置为 true 用于生产构建。 angular 更新后,选项应设置为 partial