Dynamic Import and the Cache
You'll learn: How dynamic imports interact with the module cache and why they return the same instance as static imports.
The Same Cache, Different Entry Points
When you dynamically import a module using import(), JavaScript doesn't create a new, separate instance of that module. Instead, it checks the module cache first — the exact same cache used by static imports. If the module has already been loaded (whether statically or dynamically), import() returns the cached instance.
This means:
// Static import at the top of file1.js
import { counter } from './counter.js';
// Later, in file2.js, a dynamic import
const module = await import('./counter.js');
Both receive the same module object. If the static import runs first and modifies shared state in counter.js, the dynamic import will see those changes. They share the same singleton instance.
Why This Matters
Think of the module cache like a registry at a library. Whether you request a book by walking to the desk (static import) or calling ahead (dynamic import), the library only has one copy of each book. You're always accessing the same physical copy.
This behavior is crucial for:
- Performance: No redundant parsing or execution
- State consistency: Shared state remains consistent across import styles
- Module identity:
===comparisons work as expected
You can't "reload" a module by dynamically importing it multiple times. Each import() call for the same path returns the cached module.
Key Takeaway: Dynamic imports use the same module cache as static imports — they're just another way to access modules, not a way to bypass caching or create fresh instances.