ES Modules
Use modern import and export syntax in Node.js.
Syntax
export function f() {}
import { f } from './file.js';ES Modules (ESM) are the standard JavaScript module system, using import and export. Node supports them fully.
Turning on ESM
Enable ES modules by either:
- Adding
"type": "module"to yourpackage.json, or - Naming the file with an
.mjsextension.
Named vs default exports
A module can have many named exports and one default export.
Example
// math.mjs
export function add(a, b) { return a + b; }
export default function multiply(a, b) { return a * b; }
// app.mjs
import multiply, { add } from './math.mjs';
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20When to use it
- A new Node.js 18+ project sets `"type": "module"` in package.json so all `.js` files use native ES module `import`/`export` syntax.
- A library author ships both `.cjs` and `.mjs` entry points in `package.json` `exports` so consumers using either module system can import it.
- A developer uses top-level `await` (ESM-only) to load a JSON config file before the server starts, without wrapping code in an async function.
More examples
Named ESM export and import
Demonstrates ESM named exports and the corresponding `import` destructuring syntax.
// math.mjs
export function add(a, b) { return a + b; }
export const PI = 3.14159;
// app.mjs
import { add, PI } from './math.mjs';
console.log(add(1, 2)); // 3
console.log(PI); // 3.14159Default export in ESM
Shows a default export and how to import it without braces.
// logger.mjs
export default function log(msg) {
console.log(`[LOG] ${msg}`);
}
// app.mjs
import log from './logger.mjs';
log('Server started');Top-level await in ESM
Uses top-level `await` -- available only in ES modules -- to read a file before any other code runs.
// bootstrap.mjs (requires "type":"module" in package.json)
import { readFile } from 'fs/promises';
const raw = await readFile('config.json', 'utf8');
const config = JSON.parse(raw);
console.log('Loaded config:', config.port);
Discussion