简体   繁体   中英

Circular dependency when generating Angular library

Edit

It appears that the circular dependency pops up only when using production build - ng build lib --prod


I am generating an Angular library to be used in a different Angular project. However, when compiling the code, I get a circular dependency warning in one of my barrels. This is my code:

modal.controller.ts

import { BackdropController } from './backdrop-controller';

export class ModalController {
  ...
}

Disclaimer: BackdropController does not import either ModalController or Barrel (index.controller.ts)

index.controllers.ts

export * from './backdrop-controller';
export * from './modal-controller';

Now the code above seems correct to me. ModalController is importing only BackdropController directly and not importing anything from the barrel. From standpoint of Angular application, I would say this is absolutely correct and doesn't create circular dependency.

However, When building the project. I do get a circular dependency: The output (simplified) if the build file is similar to this:

index.controller.js

export * from './backdrop.controller';
export * from './modal.controller';

modal.controller.js

import { BackdropController } from '../backdrop/backdrop.controller';
import * as i0 from '@angular/core';
import * as i1 from '../_index';

export class ModalController {
  ...
}
new i1.ModalController(...)

The problem in the compiled code seems to be the module building. On line 3, the barrel is imported as import * as i1 from '../_index' and ModalController is then added to module i1 in the end - import * as i1 from '../_index'

Is there a way to fix such circular dependency which appears only when building the code?

One solution is (tested in angular 12) to set compilationMode to full

{
  "extends": "./tsconfig.lib.json",
  "compilerOptions": {
    "declarationMap": false
  },
  "angularCompilerOptions": {
    "compilationMode": "full"
  }
}

It isn't a perfect solution but it works.
You can see what it does here

Also I found these two articles very useful about this. ( Angular Linker and Ivy library compilation )

Let me know if it did fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM