Middle
How do modules work in ES Modules?
sobes.tech AI
Answer from AI
Modules in ES Modules operate based on static analysis of imports and exports. The browser or runtime environment parses JavaScript files, determines dependencies between modules before executing the code, and creates a dependency graph.
Principles of operation:
- Static analysis: Imports and exports are determined before code execution, allowing for optimization of loading and early error detection.
- Unambiguous linking: Each import is linked to a specific export in another module.
- Single instance: A module is executed only once upon first import. All subsequent imports receive a reference to the same instance.
Module lifecycle:
- Construction: The source code of the module is parsed, imports and exports are identified. A module wrapper is created.
- Loading: All imported modules are loaded. If a dependency is not cached, a request is made to the network or filesystem.
- Linking: Imports and exports are linked. Variables and functions from imported modules become available for use. If an import cannot be resolved, an error is thrown.
- Execution: The module code is executed. All exported values become available to importing modules.
Examples:
// moduleA.js
export const name = 'Alice';
export function sayHello() {
console.log(`Hello, ${name}!`);
}
// moduleB.js
import { name, sayHello } from './moduleA.js';
console.log(name); // Output: Alice
sayHello(); // Output: Hello, Alice!
Differences from CommonJS:
| Feature | ES Modules | CommonJS |
|---|---|---|
| Linking | Static | Dynamic |
| Loading | Asynchronous (in browsers) | Synchronous (by default) |
| Export | export keyword |
module.exports |
| Import | import keyword |
require function |
| Usage | In browsers and Node.js (experimental) | In Node.js |