DEV Community

Cover image for Angular: Avoiding Circular Dependencies
John Peters
John Peters

Posted on

Angular: Avoiding Circular Dependencies

Circular Dependency Errors
Are certain to happen, but figuring them out can take a long time. I'm not sure if they are generated from WebPack or Angular, but I suspect WebPack because almost all of their error messages require a Master Degree in Error Message Interpretation.

Part of the issue is that Angular has it's own NGModule system which runs differently than the ES6 module system. Here's a few tips I've learned along the way.

  • In ES6 modules (in our functions that need references to Angular components), this style fails.
import {
 component1, 
 component2 } 
from "@name/components";
Enter fullscreen mode Exit fullscreen mode

Where @name is pseudonym for a file location where the component folder is located. This type of import implies an index.ts file listing all the components in that folder. To fix this problem:
Specify Explicit file paths instead

 import {component1} from 
  "@name/components/component1";
 import {component2} from 
  "@name/components/component2";
Enter fullscreen mode Exit fullscreen mode
  • Improper ES6 import references

Assuming the statement below is in an ES6 module, with an index.ts file, this appears to cause the error.

import {something} from "."
//do this instead
import {something} from "./moduleName"
Enter fullscreen mode Exit fullscreen mode

The more explicit form indicates that we directly want to grab something from moduleName.

Finally keep the imports segregated:

import { a, b, c} from "AModule";
import { d, e, f} from "BModule"
import { g, h, i} from "CModule"

//rather than 
import {a,b,c,d,e,g,h,1} from "@name/functions";
//where functions folder contains an index file.
Enter fullscreen mode Exit fullscreen mode

It's a bit more work but worth bypassing the dreaded circular dependency error.

Latest comments (0)