ES Module (import/export) (Node.js)

An ES Module (ESM) uses the standard JavaScript import and export syntax instead of require/module.exports. Node enables ESM for .mjs files or when package.json sets "type": "module".

Node.js

ES Modules are the official module system of the JavaScript language, the same one browsers use. You export with export const x = ... or export default ..., and import with import { x } from './file.js'. Node added full support so server and browser code can share the same syntax.

Node decides a file is ESM if it ends in .mjs, or if the nearest package.json contains "type": "module" (in which case .js files are ESM and .cjs files stay CommonJS). Mixing the two requires care: you can import CommonJS from ESM, but require() of an ESM file is restricted.

Key differences from CommonJS: import is static and hoisted (analyzed before code runs, enabling tree-shaking), the bindings are live read-only views of the exports, top-level await is allowed, and __dirname/__filename are not defined — you derive them from import.meta.url.

Syntax

import { thing } from "./file.js";
export default value;

Examples

JavaScript

// math.mjs
export function add(a, b) { return a + b; }

// app.mjs
import { add } from "./math.mjs";
console.log(add(2, 3));

Output:

5

Learn it in a lesson

See also

Back to the Dictionary