Skip to main content

๐Ÿš€ Day 6: CommonJS vs ES Modules โ€” require() vs import

Learn how Node.js modules work with CommonJS and ES Modules, understand require() vs import, and know when to use each module system in modern Node.js applications.

Updated 8 min readMarkdown

Node.js Mastery Series by CodeWithPatil โ€” Day 6


๐Ÿ“– Table of Contents

  • ๐Ÿ‘‹ Introduction

  • ๐Ÿ“š Prerequisites

  • ๐Ÿค” What is a Module System?

  • ๐Ÿš€ Why Do We Need a Module System?

  • โš™๏ธ How Module Systems Work

  • ๐Ÿ“ฆ CommonJS

  • ๐ŸŒ ES Modules

  • ๐Ÿ’ป Practical Examples

  • โš”๏ธ CommonJS vs ES Modules

  • ๐Ÿ”„ require() vs import

  • ๐Ÿ”„ module.exports vs export

  • โš™๏ธ How to Enable ES Modules

  • ๐ŸŒ Real-World Use Cases

  • โš ๏ธ Common Mistakes

  • ๐Ÿ’ก Best Practices

  • ๐Ÿง  Interview Questions

  • โœ… Key Takeaways

  • ๐Ÿ“š What's Next?

  • ๐Ÿ’™ CodeWithPatil


๐Ÿ‘‹ Introduction

In Day 5 โ€” Understanding Node.js Modules, we explored:

  • Core Modules

  • Local Modules

  • Third-Party Modules

  • require()

  • Creating reusable modules

However, there is another important concept every Node.js developer must understand:

Node.js supports multiple module systems.

The two most common module systems are:

CommonJS (CJS)

const fs = require("fs");

ES Modules (ESM)

import fs from "fs";

Both statements import modules, but they belong to different module systems.

This naturally raises an important question:

What is the difference between require() and import?

Let's understand everything step by step. ๐Ÿš€


๐Ÿ“š Prerequisites

Before reading this article, make sure you're familiar with:

โœ… Basic JavaScript Functions

โœ… Objects and Arrays

โœ… Node.js Fundamentals

โœ… Node.js Modules (Day 5)

โœ… package.json


๐Ÿค” What is a Module System?

A module system defines how JavaScript code can be:

  • Organized

  • Split into multiple files

  • Exported

  • Imported

  • Reused

  • Shared across applications

Imagine your application contains:

app.js
math.js
user.js
database.js

Instead of writing all logic inside app.js, you can keep related functionality in separate files and import only what you need.

That's exactly what a module system helps us achieve.

Node.js primarily supports two module systems:

  1. CommonJS (CJS)

  2. ES Modules (ESM)


๐Ÿš€ Why Do We Need a Module System?

Without modules:

function add() {}
function subtract() {}
function connectDB() {}
function loginUser() {}
function sendEmail() {}

As applications grow, maintaining such files becomes difficult.

Benefits of Modules

โœ… Better organization

โœ… Code reusability

โœ… Easier maintenance

โœ… Improved scalability

โœ… Team collaboration

โœ… Cleaner architecture


๐Ÿ“ฆ CommonJS (CJS)

CommonJS is the traditional module system used by Node.js.

It uses:

require()

for importing modules and:

module.exports

for exporting modules.

Example:

const math = require("./math");
module.exports = math;

๐Ÿ” Understanding require()

require() loads a module and returns whatever that module exports.

const path = require("path");

console.log(path.join("users", "data"));

Output:

users/data

๐Ÿ“ค Understanding module.exports

math.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract,
};

app.js

const math = require("./math");

console.log(math.add(10, 5));
console.log(math.subtract(10, 5));

Output:

15
5

Flow:

math.js
   โ†“
module.exports
   โ†“
app.js
   โ†“
require("./math")

๐ŸŒ What Are ES Modules (ESM)?

ES Modules are the official JavaScript module system introduced by ECMAScript.

Instead of:

require()

they use:

import

Instead of:

module.exports

they use:

export

Example:

import { add } from "./math.js";
export function add(a, b) {
  return a + b;
}

๐Ÿ“ฅ Understanding import

import { add } from "./math.js";

console.log(add(10, 5));

Flow:

import
   โ†“
Loads exported functionality
   โ†“
from another file

๐Ÿ“ค Understanding export

Named Export

export function add(a, b) {
  return a + b;
}

Import:

import { add } from "./math.js";

Default Export

export default function greet(name) {
  return `Hello ${name}`;
}

Import:

import greet from "./greet.js";

console.log(greet("Developer"));

Output:

Hello Developer

๐Ÿ’ป Practical Examples

๐Ÿ“ฆ CommonJS Practical Example

Project Structure

commonjs-demo/
โ”‚
โ”œโ”€โ”€ app.js
โ”œโ”€โ”€ calculator.js
โ””โ”€โ”€ package.json

calculator.js

function multiply(a, b) {
  return a * b;
}

function divide(a, b) {
  return a / b;
}

module.exports = {
  multiply,
  divide,
};

app.js

const calculator = require("./calculator");

console.log(calculator.multiply(5, 4));
console.log(calculator.divide(20, 5));

Output:

20
4

๐ŸŒ ES Modules Practical Example

Project Structure

esm-demo/
โ”‚
โ”œโ”€โ”€ app.js
โ”œโ”€โ”€ calculator.js
โ””โ”€โ”€ package.json

calculator.js

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

app.js

import { add, subtract } from "./calculator.js";

console.log(add(10, 5));
console.log(subtract(10, 5));

Output:

15
5

โš™๏ธ How to Enable ES Modules

Option 1: "type": "module"

package.json

{
  "name": "esm-demo",
  "version": "1.0.0",
  "type": "module"
}

Option 2: .mjs

app.mjs
calculator.mjs

Example:

import { add } from "./calculator.mjs";

โš”๏ธ CommonJS vs ES Modules

Feature CommonJS ES Modules
Import require() import
Export module.exports export
Default Export CommonJS Pattern export default
Extension .js .js, .mjs
Standard โŒ No โœ… Yes
Browser Support โŒ No โœ… Yes

๐Ÿ”„ require() vs import

CommonJS

const express = require("express");

ES Modules

import express from "express";

๐Ÿ”„ module.exports vs export

CommonJS

function add(a, b) {
  return a + b;
}

module.exports = {
  add,
};

Import:

const { add } = require("./math");

ES Modules

export function add(a, b) {
  return a + b;
}

Import:

import { add } from "./math.js";

๐ŸŒ Real-World Use Cases

  • Building REST APIs

  • Working with Express.js

  • Creating npm packages

  • Building reusable libraries

  • Migrating old Node.js applications

  • Working with TypeScript projects


โš ๏ธ Common Mistakes

1. Mixing require() and import

const fs = require("fs");
import express from "express";

Avoid mixing unless you understand project configuration.

2. Forgetting "type": "module"

{
  "type": "module"
}

3. Forgetting File Extensions

โŒ Wrong

import { add } from "./math";

โœ… Correct

import { add } from "./math.js";

4. Using Curly Braces Incorrectly

Named Export:

export function add() {}
import { add } from "./math.js";

Default Export:

export default function add() {}
import add from "./math.js";

๐Ÿ’ก Best Practices

โœ… Use ES Modules in new projects

โœ… Learn both CJS and ESM

โœ… Keep imports organized

โœ… Understand named vs default exports

โœ… Avoid unnecessary mixing

โœ… Use small reusable modules


๐Ÿง  Interview Questions

What is CommonJS?

A Node.js module system that uses require() and module.exports.

What are ES Modules?

The official JavaScript module system that uses import and export.

Difference between require() and import?

require() belongs to CommonJS. import belongs to ES Modules.

How do you enable ESM?

Using:

{
  "type": "module"
}

or .mjs files.


โœ… Key Takeaways

โœ… CommonJS uses:

require()
module.exports

โœ… ES Modules use:

import
export

โœ… ESM is the modern JavaScript standard.

โœ… Learn both systems because real-world projects use both.

Memory Trick

CommonJS
   โ”œโ”€โ”€ require()
   โ””โ”€โ”€ module.exports

ES Modules
   โ”œโ”€โ”€ import
   โ””โ”€โ”€ export

๐Ÿ“š What's Next?

Day 7 โ€” Node.js Global Objects: global, __dirname, and __filename

You'll learn:

  • The global object

  • __dirname

  • __filename

  • CommonJS vs ESM differences

  • Practical examples

  • Real-world use cases

See you in Day 7! ๐Ÿš€


๐Ÿ’™ Follow CodeWithPatil

If you enjoy practical, real-world tutorials on Backend Development, Cloud Computing, DevOps, and modern software engineering, follow CodeWithPatil for project-based learning.


๐Ÿ’ฌ Feedback & Support

Have a question, found an issue, or have suggestions for future topics?

Leave a comment below. I'd love to hear from you. Your feedback helps improve future articles and supports the learning community.

โญ If you found this article helpful, leave a reaction and share it with your developer friends.

Happy Coding! ๐Ÿš€

About the author

  • # Hi, I'm Sumit Patil ๐Ÿ‘‹ a Senior Backend Software Engineer with 7+ years of experience designing scalable backend systems and cloud-native applications. I specialize in Node.js, NestJS, TypeScript, GraphQL, PostgreSQL, MongoDB, AWS, Microservices, and DevOps. ๐Ÿ† Smart Gujarat for New India Hackathon Winner

No comments yet. Be the first to comment.