Middle
Kuidas töötavad ES Modules'i moodulid?
sobes.tech AI
Vastus AI-lt
ES Modules work 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 optimization of loading and early error detection.
- Unambiguous linking: Each import is linked to a specific export in another module.
- Single instance: The module is executed only once at the first import. All subsequent imports reference the same instance.
Module lifecycle:
- Construction: The source code of the module is parsed, imports and exports are identified. The module wrapper is created.
- Loading: All imported modules are loaded. If a dependency is not cached, a request is made to the network or file system.
- 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 browser) | Synchronous |
| Export | export keyword |
module.exports |
| Import | import keyword |
require function |
| Usage | In browser and Node.js (experimental) | In Node.js |