π ES Modules (ESM)
ES Modules is the modern JavaScript module system, supported by both browsers and Node.js.
Export with
exportImport with
importLoads modules asynchronously
π Features
Native support in browsers
Static imports β enables better tree-shaking
Clear, readable syntax
Works natively with modern tools like React, Vite, and Next.js
π§ͺ Sample Code
math.js
export function add(a, b) {
return a + b;
}app.js
import { add } from './math.js';
console.log(add(2, 3)); // 5π When to Use ES Modules
π¨ Modern frontend development
π Full-stack apps spanning Node.js and the browser
π‘ Good to Know
Node.js doesn't use ESM by default β add
"type": "module"topackage.json, or name files.mjs.ESM supports top-level
awaitβ no wrapping in an async function needed.CJS modules can't be
require()'d from ESM directly, but ESM files can use dynamicimport()to load a CJS module.
βοΈ CommonJS vs ES Modules, at a Glance
Feature | CommonJS (CJS) | ES Modules (ESM) |
|---|---|---|
Import syntax |
|
|
Export syntax |
|
|
Default in Node.js | β Yes | β Needs config |
Loading | Synchronous | Asynchronous |
Works in browser? | β Not directly | β Yes |
File extension |
|
|
Top-level | β No | β Yes |
Tree shaking | β No | β Yes (with bundlers like Webpack) |