Detect and resolve TypeScript/JavaScript circular import dependencies. Use when:
(1) "Cannot access 'X' before initialization" at runtime, (2) Import returns
undefined unexpectedly, (3) "ReferenceError: Cannot access X before initialization",
(4) Type errors that disappear when you change import order, (5) Jest/Vitest tests
fail with undefined imports that work in browser.
Detect and resolve TypeScript/JavaScript circular import dependencies. Use when:
(1) "Cannot access 'X' before initialization" at runtime, (2) Import returns
undefined unexpectedly, (3) "ReferenceError: Cannot access X before initialization",
(4) Type errors that disappear when you change import order, (5) Jest/Vitest tests
fail with undefined imports that work in browser.
author
Claude Code
version
1.0.0
date
2024-03-10T00:00:00.000Z
TypeScript Circular Dependency Detection and Resolution
Problem
Circular dependencies occur when module A imports from module B, which imports
(directly or indirectly) from module A. TypeScript compiles successfully, but at
runtime, one of the imports evaluates to undefined because the module hasn't
finished initializing yet.
Context / Trigger Conditions
Common error messages:
ReferenceError: Cannot access 'UserService' before initialization
TypeError: Cannot read properties of undefined (reading 'create')
TypeError: (0 , _service.doSomething) is not a function
Symptoms that suggest circular imports:
Import is undefined even though the export exists
Error only appears at runtime, not during TypeScript compilation
Moving an import statement changes which import is undefined
Tests fail but the app works (or vice versa)
Adding console.log at the top of a file changes behavior