Loading lessons...
ES Modules (ESM) in Node.js
Modern ES Modules (import / export)
Node.js supports ECMAScript Modules (ESM), which use static analysis and asynchronous loading with import and export statements.
Enabling ES Modules in Node.js
You can enable ES Modules by either:
- Setting
"type": "module"in yourpackage.json. - Using the
.mjsfile extension (e.g.,server.mjs).
Named and Default Exports
// utils.mjs - Named exports & Default export
export const API_VERSION = "v2";
export function formatUser(name) {
return name.trim().toUpperCase();
}
export default class ApiClient {
connect() {
console.log("Connected to API");
}
}
// index.mjs - Importing ESM
import ApiClient, { API_VERSION, formatUser } from "./utils.mjs";
const client = new ApiClient();
console.log(API_VERSION, formatUser(" alice "));
CommonJS vs ES Modules Key Differences
| Feature | CommonJS (CJS) | ES Modules (ESM) |
|---|---|---|
| Loading | Synchronous (require) | Asynchronous / Static (import) |
| Top-Level Async | Not natively supported | Supported (Top-level await) |
| Special Vars | __dirname, __filename available | Use import.meta.url with fileURLToPath |
| File Extensions | Relative paths omit extension | Strict relative path with extension required |
// Emulating __dirname in ES Modules
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
TL;DR
- Set
"type": "module"inpackage.jsonto useimport/export. - ESM allows top-level
await. - Replaces
__dirnamewithimport.meta.url.