04. Cyclic Dependencies

ES6 modules support cyclic dependencies automatically:

//------ a.js ------
import { bar } from "b"; // (i)
export function foo() {
  bar(); // (ii)
}

//------ b.js ------
import { foo } from "a"; // (iii)
export function bar() {
  if (Math.random()) {
    foo(); // (iv)
  }
}

This code works, because imports are views on exports. That means that even unqualified imports (such as bar in line ii and foo in line iv) are indirections that refer to the original data.

Thus, in the face of cyclic dependencies, it doesn’t matter whether you access a named export via an unqualified import or via its module: There is an indirection involved in either case and it always works.

Last updated