SyntaxStudy
Sign Up
JavaScript Advanced 5 min read

Circular Imports

Circular Imports

Circular imports occur when module A imports from module B, and module B imports from module A. They can work in ES modules but may cause initialization order issues.

Example
// a.js
import { getB } from "./b.js";
export function getA() { return "A"; }
console.log(getB()); // might be undefined if b.js not fully loaded yet

// b.js
import { getA } from "./a.js";
export function getB() { return "B + " + getA(); }

// Solution: use lazy evaluation
export function getB() {
  const { getA } = require("./a.js"); // import inside function
}
Pro Tip

Circular dependencies often signal poor module boundaries — refactor shared code into a third module that both can import.