# 🚀 Day 6: CommonJS vs ES Modules — require() vs import

> **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)

```javascript
const fs = require("fs");
```

### ES Modules (ESM)

```javascript
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:

```text
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:

```javascript
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:

```javascript
require()
```

for importing modules and:

```javascript
module.exports
```

for exporting modules.

Example:

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

```javascript
module.exports = math;
```

* * *

## 🔍 Understanding `require()`

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

```javascript
const path = require("path");

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

Output:

```text
users/data
```

* * *

## 📤 Understanding `module.exports`

### math.js

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

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

module.exports = {
  add,
  subtract,
};
```

### app.js

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

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

Output:

```text
15
5
```

Flow:

```text
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:

```javascript
require()
```

they use:

```javascript
import
```

Instead of:

```javascript
module.exports
```

they use:

```javascript
export
```

Example:

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

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

* * *

## 📥 Understanding `import`

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

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

Flow:

```text
import
   ↓
Loads exported functionality
   ↓
from another file
```

* * *

## 📤 Understanding `export`

### Named Export

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

Import:

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

### Default Export

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

Import:

```javascript
import greet from "./greet.js";

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

Output:

```text
Hello Developer
```

* * *

# 💻 Practical Examples

## 📦 CommonJS Practical Example

### Project Structure

```text
commonjs-demo/
│
├── app.js
├── calculator.js
└── package.json
```

### calculator.js

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

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

module.exports = {
  multiply,
  divide,
};
```

### app.js

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

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

Output:

```text
20
4
```

* * *

## 🌐 ES Modules Practical Example

### Project Structure

```text
esm-demo/
│
├── app.js
├── calculator.js
└── package.json
```

### calculator.js

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

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

### app.js

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

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

Output:

```text
15
5
```

* * *

# ⚙️ How to Enable ES Modules

## Option 1: `"type": "module"`

### package.json

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

* * *

## Option 2: `.mjs`

```text
app.mjs
calculator.mjs
```

Example:

```javascript
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

```javascript
const express = require("express");
```

### ES Modules

```javascript
import express from "express";
```

* * *

# 🔄 `module.exports` vs `export`

### CommonJS

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

module.exports = {
  add,
};
```

Import:

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

### ES Modules

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

Import:

```javascript
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`

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

Avoid mixing unless you understand project configuration.

### 2\. Forgetting `"type": "module"`

```json
{
  "type": "module"
}
```

### 3\. Forgetting File Extensions

❌ Wrong

```javascript
import { add } from "./math";
```

✅ Correct

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

### 4\. Using Curly Braces Incorrectly

Named Export:

```javascript
export function add() {}
```

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

Default Export:

```javascript
export default function add() {}
```

```javascript
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:

```json
{
  "type": "module"
}
```

or `.mjs` files.

* * *

# ✅ Key Takeaways

✅ CommonJS uses:

```javascript
require()
module.exports
```

✅ ES Modules use:

```javascript
import
export
```

✅ ESM is the modern JavaScript standard.

✅ Learn both systems because real-world projects use both.

### Memory Trick

```text
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! 🚀**
