JavaScript Fundamentals / Modules

Module System in JS

πŸ“Œ What is a Module?

A module is a self-contained file or block of code that encapsulates logic and functionality. It helps organize large codebases into manageable parts and promotes reusability, maintainability, and namespace isolation.


πŸ“œ Why Use Modules?

  • πŸ” Code Reusability – Use the same code in different files.

  • 🧠 Maintainability – Easier to debug and manage.

  • 🧼 Encapsulation – Prevent variable/function name conflicts.

  • πŸ“ Separation of Concerns – Each module handles a specific task.


πŸ•°οΈ Evolution of Module Systems in JS

Module Type

Description

Used In

IIFE

Immediate Invoked Function Expression

Very early JS

CommonJS

Uses require() and module.exports

Node.js (synchronous)

AMD

Uses define() (Asynchronous)

Browsers, RequireJS

ES Modules

Uses import/export syntax

ES6+ (modern JS)

Today, ES6 Modules (ESM) are the standard for both browser and server-side JavaScript.


βœ… ES6 Modules (Modern JavaScript)

🧱 Basic Concepts:

  • export – Makes a variable/function/class available to other files

  • import – Brings in variables/functions from another file


✨ How to Use ES Modules

πŸ“‚ Example Project Structure

project/
β”‚
β”œβ”€β”€ index.html
β”œβ”€β”€ main.js
β”œβ”€β”€ utils
β”‚   β”œβ”€β”€ math.js
β”‚   └── greet.js

βœ… Exporting

πŸ‘‰ Named Export (you can export multiple things)

// utils/math.js
export const PI = 3.14159;

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

πŸ‘‰ Default Export (only one default per file)

// greet.js
export default function greet(name) {
  return `Hello, ${name}!`;
}

βœ… Importing

πŸ‘‰ Import named exports

// main.js
import { PI, add } from './utils/math.js';

console.log(PI);            // 3.14159
console.log(add(2, 3));     // 5

πŸ‘‰ Import default export

import greet from './greet.js';

console.log(greet("Codeveda"));  // Hello, Codeveda!

πŸ‘‰ Rename imports

import { add as addition } from './mathUtils.js';

console.log(addition(10, 20));  // 30

βœ… Combine Default and Named Imports

import greet, { PI, add } from './combined.js';

πŸ›œ Using ES Modules in Browser

βœ… Add type="module" to <script>

<!DOCTYPE html>
<html>
<head>
  <title>ES6 Modules</title>
</head>
<body>
  <script type="module" src="./main.js"></script>
</body>
</html>

πŸ›‘ Without type="module", import/export won't work in browser!


βš™οΈ ES Modules in Node.js

βœ… Use .mjs extension or set "type": "module" in package.json

{
  "type": "module"
}

Then, in your JS files:

// utils.mjs or utls.js
export function multiply(a, b) {
  return a * b;
}
// app.mjs or app.js
import { multiply } from './utils.mjs';
console.log(multiply(4, 5));  // 20

πŸ” Module Scope

Each module has its own scope:

  • Variables and functions defined in one module are not visible in other files unless exported.

  • This avoids global namespace pollution.