#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 4 of 62easy

What is the difference between CommonJS and ES Modules?

Understanding module systems in Node.js.

What You'll Learn

  • CommonJS syntax
  • ES Modules syntax
  • Key differences

CommonJS (CJS)

code.jsJavaScript
// Exporting
module.exports = { add, subtract };
// or
exports.add = add;

// Importing
const { add } = require('./math');
const fs = require('fs');

ES Modules (ESM)

code.jsJavaScript
// Exporting
export const add = (a, b) => a + b;
export default function subtract(a, b) { return a - b; }

// Importing
import { add } from './math.js';
import subtract from './math.js';
import * as math from './math.js';

Key Differences

FeatureCommonJSES Modules
Syntaxrequire/exportsimport/export
LoadingSynchronousAsynchronous
File Extension.js, .cjs.mjs or "type": "module"
Top-level await❌ No✅ Yes
Tree shaking❌ No✅ Yes

Enabling ESM in Node.js

data.jsonJSON
// package.json
{
  "type": "module"
}

Or use .mjs file extension.

Interop

code.jsJavaScript
// Import CJS in ESM
import pkg from 'commonjs-package';

// Import ESM in CJS (dynamic import)
async function loadESM() {
  const { add } = await import('./esm-module.mjs');
}