Course contentsShow
← JavaScript
Lesson 1540 of 2,72333. JavaScript in Node.jsFree lesson

CommonJS require() vs ES Module import

Understand the two module systems in Node.js and their fundamental differences in syntax and behavior.

CommonJS require() vs ES Module import

You'll learn the fundamental syntax and behavioral differences between Node.js's two module systems.

Two Ways to Load Code

Node.js supports two module systems for organizing and sharing code between files:

  1. CommonJS (CJS) — the original system using require() and module.exports
  2. ES Modules (ESM) — the newer, standardized system using import and export

Think of them as two different languages for the same conversation: both let modules talk to each other, but with different grammar and rules.

Syntax Differences

CommonJS:

// Loading a module
const fs = require('fs');
const myModule = require('./myModule');

// Exporting
module.exports = { name: 'Alice' };

ES Modules:

// Loading a module
import fs from 'fs';
import { readFile } from 'fs';
import myModule from './myModule.js';

// Exporting
export default { name: 'Alice' };
export const greeting = 'Hello';

Behavioral Differences

CommonJS loads modules synchronously at runtime. You can call require() anywhere in your code, even inside conditionals or functions. It's dynamic and flexible.

ES Modules are statically analyzed before execution. import statements must appear at the top level of your file (not inside functions), enabling better optimization and tree-shaking.

CJS creates a copy of exported values, while ESM creates a live binding—changes in the original module reflect in imports.

Key Takeaway: CommonJS uses require() with synchronous, dynamic loading; ES Modules use import with static, top-level declarations. Both coexist in Node.js, but ESM is the modern standard.