Fix Circular Module Dependencies in JavaScript & TypeScript

Question

js circular dependencies, for example, module A and module B both extend from the base class module C, but some methods in C will refer to A or B. At this time, A and C, B and C are interdependent relationships. Modules and types are often imported in ts, and mutual references are very common.

The following code shows this circular dependency.

// --- Entry file index.js ---
import { C } from "./C";

new C();

// --- Base class module C.js ---
import { A } from "./A";
import { B } from "./B";

export class C {}

// --- submodule A.js ---
// The import here will report an error: Super expression must either be null or a function
import { C } from "./C";
export class A extends C {
  constructor() {
    super("");
  }
}

// --- submodule B.js ---
import { C } from "./C";
export class B extends C {
  constructor() {
    super("");
  }
}

Here is a simple example to demonstrate that an error cannot be executed after a circular reference

Solution

Create an additional public module to import all modules and then export them. If a module needs to use other modules, it is imported from this public module for use, which is equivalent to being a transit station.

// --- Entry file index.js ---
import { C } from "./common";

new C();

// --- Common module export file common.js ---
// Note that export * from "./C"; must be written at the top, because the C module is a module dependent on A and C and needs to be cached first
export * from "./C";
export * from "./A";
export * from "./B";

// --- Base class module C.js ---
import { A } from "./common";
import { B } from "./common";

export class C {}

// --- submodule A.js ---
// The import here will report an error Super expression must either be null or a function
import { C } from "./common";
export class A extends C {
  constructor() {
    super("");
  }
}

// --- submodule B.js ---
import { C } from "./common";
export class B extends C {
  constructor() {
    super("");
  }
}

Here is a simple example to demonstrate how to solve the circular reference problem after exporting using public modules.

Reference

Comments