This project is a demo that shows the problem caused by circular dependencies between JavaScript modules when bundled with Webpack.
This demo reproduces the following circular dependency situation:
moduleA.jsimportsmoduleB.jsmoduleB.jsimportsmoduleA.js- At runtime, an
Uncaught TypeError: helloA is not a functionerror occurs
src/
├── index.js # Entry point
├── moduleA.js # Module A
└── moduleB.js # Module B (circular dependency)
Install dependencies:
npm install
Start the development server:
npm start
Or, create a production build:
npm run build
The following error will appear in the browser console:
Hello from A
Hello from B
Uncaught TypeError: helloA is not a function
This issue is due to the ES Modules specification. In modules with circular dependencies, some functions or variables may be undefined depending on the timing of initialization.
In this demo:
- When
moduleB.jsimportsmoduleA.js,helloAis not yet defined moduleA.jsis executed first, defines thehelloAfunction, and then callshelloB- Inside
helloB, it tries to callhelloA, but at this point,helloAisundefined
Best practices to avoid circular dependencies:
- Review your module structure and make dependencies one-way
- Extract common functionality into a separate module
- Use dynamic imports
- Import inside functions (runtime import)
Real example for fixing circular dependency in entire codebase: https://github.com/replayio/devtools/pulls?q=sort%3Aupdated-desc+is%3Apr+Circular+Import+is%3Aclosed