Node.js ES Modules
Node.js ES Modules (ESM)
Node.js supports two module systems:
-
CommonJS (CJS) → uses
require()&module.exports -
ES Modules (ESM) → uses
import&export
ES Modules are the modern JavaScript module standard, used in browsers and modern Node.js apps.
⭐ Why Use ES Modules?
✔ Cleaner syntax
✔ Works in both Node.js and browsers
✔ Supports tree-shaking (remove unused code)
✔ Better for large applications
✔ Future standard of JavaScript
1️⃣ Enabling ES Modules in Node.js
You can enable ES module support in two ways:
Option 1: Add "type": "module" in package.json
Then you can use:
-
.jsfor ESM code -
import/exportsyntax
Option 2: Use .mjs extension
Files ending with .mjs are treated as ES modules automatically.
2️⃣ Exporting in ES Modules
You can export:
-
default values
-
named values
-
functions
-
objects
-
classes
✅ Named Exports
file: math.js
Importing named exports:
✅ Default Export
file: user.js
Importing default export:
⚠ You can have only one default export per file.
✅ Mixing Default + Named Exports
person.js
Importing:
3️⃣ Exporting Everything at Once
file: utils.js
4️⃣ Importing Everything
5️⃣ ES Module Features
🚀 Top-level Await (No async function needed)
Works only in ES modules, not in CommonJS.
🚀 Strict Mode by Default
ESM automatically uses "use strict";
No need to declare it manually.
🚀 No require(), use import() instead
Example: dynamic import:
6️⃣ Differences Between CommonJS and ES Modules
| Feature | CommonJS (CJS) | ES Modules (ESM) |
|---|---|---|
| Import | require() | import |
| Export | module.exports | export |
| Sync/Async | Synchronous | Asynchronous |
| Top-level await | ❌ No | ✔ Yes |
| Browser support | ❌ No | ✔ Yes |
| Strict mode | Optional | Always strict |
7️⃣ When to Use ES Modules?
Use ESM when:
✔ working with modern JavaScript
✔ building frontend + backend together
✔ using tools like Babel, Vite, Webpack
✔ wanting cleaner and future-proof syntax
8️⃣ Quick Example Project
math.js
app.js
package.json
Run:
