Skip to content

CommonJS and ES Modules

  • 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+).
  • Default module system in Nodejs (until recently).
  • Uses require() to load modules and module.exports or exports to export.
  • Load modules synchronously.
  • Example:
math.js
function add(a, b){
return a+b
}
module.exports = { add } // export
app.js
const math = require('math') // import
console.log(math.add(1,4)) // Output -> 5
  • Introduced in ES6 (ECMAScript 2015).
  • Uses import and export.
  • Load modules asynchronously.
  • Supported in Nodejs 12+
  • To enable:
    • Use type: module in package.json.
    • OR
    • Use .mjs file extension.
  • Example:
math.js
export function add(a, b){ // export
return a+b
}
app.js
import {math} from 'math.js' // import
console.log(math.add(1,4)) // Output -> 5
Featurerequire (CJS)import (ESM)
Syntaxconst x = require("x")import x from "x"
Exportmodule.exports = ...export / export default
Sync/AsyncSynchronous (blocks until loaded)Asynchronous (non-blocking)
ScopeWorks anywhere (can call conditionally)Must be at top-level (static import)
Node.js defaultYes (before ES6 modules)No (must enable via "type":"module" or .mjs)
Browser supportโŒ (needs bundler)โœ… Native in modern browsers
  • โœ… 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).
  • 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')
    • In CJS : import ESM with import() (async).
  • CommonJS (require) = โ€œCall a friend whenever you need them (synchronous).โ€
  • ESM (import) = โ€œSchedule a meeting in advance (asynchronous, structured).โ€