SyntaxStudy
Sign Up
Node.js ES Modules (import / export)
Node.js Beginner 9 min read

ES Modules (import / export)

ES Modules (ESM) are the modern JavaScript module standard supported natively in Node.js 12+. Use import and export statements. Either name your files .mjs or add "type": "module" to package.json.

ESM supports static analysis, tree-shaking, and top-level await.

Example
// package.json — enable ESM for the whole project:
// { "type": "module" }

// --- utils.mjs (named exports) ---
export function greet(name) {
    return `Hello, ${name}!`;
}

export const VERSION = '1.0.0';

// Default export:
export default function multiply(a, b) {
    return a * b;
}

// --- main.mjs (importing) ---
import multiply, { greet, VERSION } from './utils.mjs';

console.log(greet('Alice'));    // Hello, Alice!
console.log(VERSION);           // 1.0.0
console.log(multiply(4, 5));    // 20

// Dynamic import (works in both CJS and ESM):
async function loadModule() {
    const { greet } = await import('./utils.mjs');
    console.log(greet('Bob'));
}

loadModule();

// Built-ins with ESM:
import { readFile } from 'fs/promises';
import { join } from 'path';