Node.js: Code Outside the Browser / Working with Modules

ES Module

🌐 ES Modules (ESM)

ES Modules is the modern JavaScript module system, supported by both browsers and Node.js.

  • Export with export

  • Import with import

  • Loads 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" to package.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 dynamic import() to load a CJS module.


βš”οΈ CommonJS vs ES Modules, at a Glance

Feature

CommonJS (CJS)

ES Modules (ESM)

Import syntax

const x = require('x')

import x from 'x'

Export syntax

module.exports = x

export default x / export {...}

Default in Node.js

βœ… Yes

❌ Needs config

Loading

Synchronous

Asynchronous

Works in browser?

❌ Not directly

βœ… Yes

File extension

.js

.mjs (or .js with config)

Top-level await

❌ No

βœ… Yes

Tree shaking

❌ No

βœ… Yes (with bundlers like Webpack)