ES Modules (Advanced)
Introduction to ES Modules
ES Modules (ESM) are the official, standardized module system for JavaScript. Unlike CommonJS (require/module.exports), ESM uses static analysis and supports tree shaking, making it more efficient for modern web development.
- Static imports/exports (analyzed at compile time)
- Asynchronous by nature
- Strict mode by default
- Better tooling support (tree shaking, bundling)
1. Basic Module Syntax
JavaScript Editor
Key Points:
- Named exports allow multiple exports per module
- Default export is the primary export
- Imports are hoisted to the top
3. Module Re-exporting Patterns
JavaScript Editor
Re-exporting helps create cleaner public APIs and organize code.
5. Import Meta
JavaScript Editor
import.meta provides module-specific metadata.
2. Dynamic Imports
JavaScript Editor
Dynamic imports enable code splitting and lazy loading.
4. Top-level Await
JavaScript Editor
Available in ES2022 for modules only. Great for initialization.
6. Circular Dependencies
JavaScript Editor
⚠️ While supported, circular dependencies can lead to subtle bugs.
Module Loading Sequence
| Phase | Description | Synchronous? |
|---|---|---|
| Construction | Parse module, find imports | Yes |
| Instantiation | Set up memory, bind exports/imports | Yes |
| Evaluation | Execute module code | Yes (but imports are async) |