CommonJS and ES Modules
๐น 1. Modules in Node.js
Section titled โ๐น 1. Modules in Node.jsโ- Modules let you split code into separate files and reuse them.
- In Node.js, there are two main module systems:
- CommonJS (CJS) -> older, default in Node.js(before ES6).
- ES Modules (ESM) -> newer, standardized in JavaScript(ES6+).
๐น 2. CommonJS (CJS)
Section titled โ๐น 2. CommonJS (CJS)โ- Default module system in Nodejs (until recently).
- Uses
require()to load modules andmodule.exportsorexportsto export. - Load modules synchronously.
- Example:
function add(a, b){ return a+b } module.exports = { add } // export const math = require('math') // import console.log(math.add(1,4)) // Output -> 5๐น 3. ES Modules (ESM)
Section titled โ๐น 3. ES Modules (ESM)โ- Introduced in ES6 (ECMAScript 2015).
- Uses
importandexport. - Load modules asynchronously.
- Supported in
Nodejs 12+ - To enable:
- Use
type: moduleinpackage.json. - OR
- Use
.mjsfile extension.
- Use
- Example:
export function add(a, b){ // export return a+b } import {math} from 'math.js' // import console.log(math.add(1,4)) // Output -> 5๐น 4. require vs import
Section titled โ๐น 4. require vs importโ| Feature | require (CJS) | import (ESM) |
|---|---|---|
| Syntax | const x = require("x") | import x from "x" |
| Export | module.exports = ... | export / export default |
| Sync/Async | Synchronous (blocks until loaded) | Asynchronous (non-blocking) |
| Scope | Works anywhere (can call conditionally) | Must be at top-level (static import) |
| Node.js default | Yes (before ES6 modules) | No (must enable via "type":"module" or .mjs) |
| Browser support | โ (needs bundler) | โ Native in modern browsers |
๐น 5. When to Use Which?
Section titled โ๐น 5. When to Use Which?โ- โ
CommonJS (require)
- Older Node.js projects.
- Packages still written in CJS.
- If you need dynamic imports (conditionally load a module).
- โ
ESM (import)
- Modern Node.js apps.
- Frontend + Backend consistency (since browser uses
import). - Tree-shaking (Removes unused code in bundlers like Webpack, Rollup).
๐น 6. Mixing Them
Section titled โ๐น 6. Mixing Themโ- Sometimes we need to use both (e.g., using an older npm package inside an ES Module project).
- In ESM: Use dynamic import
- Syntax:
const lodash = await import('lodash')
- Syntax:
- In CJS : import ESM with
import()(async).
- In ESM: Use dynamic import
โก Analogy
Section titled โโก Analogyโ- CommonJS (
require) = โCall a friend whenever you need them (synchronous).โ - ESM (
import) = โSchedule a meeting in advance (asynchronous, structured).โ