ECMAScript #
ECMAScript Modules (ESM) support in Node.js brings a modern and standardized approach to handling modules in server-side JavaScript. Introduced to Node.js in version 13.2.0, ESM allows developers to use the import and export syntax familiar from browser-side JavaScript, replacing the CommonJS require syntax. Below is an overview of the basic ESM features in Node.js:
Module Syntax: #
In ESM, modules are created using the import and export keywords. This aligns Node.js with the ECMAScript standard, providing a consistent module system.
// Exporting module
// file: myModule.js
export const greet = name => `Hello, ${name}!`;
// Importing module
// file: main.js
import { greet } from './myModule.js';
console.log(greet('Node.js'));
File Extension: #
Unlike CommonJS, which infers file extensions, ESM requires specifying the file extension in the import statement.
// ESM
import { greet } from './myModule.js';
// CommonJS
const greet = require('./myModule');
Named Exports and Default Export: #
ESM allows named exports and a default export in a single module.
// Named exports
export const sum = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// Default export
const greet = name => `Hello, ${name}!`;
export default greet;
Circular Dependencies: #
ESM handles circular dependencies more predictably than CommonJS. When a module is circularly dependent, ESM returns an unfinished copy of the module.
Dynamic Import: #
ESM supports dynamic import, allowing developers to load modules asynchronously.
const dynamicModule = await import('./myDynamicModule.js');
console.log(dynamicModule.default());
Top-Level this: #
In ESM, the top-level this value inside a module is undefined, aligning with the behavior in browser-side JavaScript.
Migrating from CommonJS: #
Node.js provides a smooth migration path from CommonJS to ESM. Developers can use the .mjs extension for ESM files and keep using .js for CommonJS files. However, this requires setting “type”: “module” in the package.json file.
ESM in Node.js enhances code maintainability and promotes better interoperability with browser-side JavaScript. It introduces a more modern syntax for module handling, aligning with ECMAScript standards. While ESM and CommonJS can coexist in Node.js, migrating to ESM provides developers with the advantages of a standardized module system, dynamic imports, and improved handling of circular dependencies. As Node.js continues to evolve, embracing ESM empowers developers to write more modular, maintainable, and future-proof code.