π 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 | Node.js (synchronous) |
AMD | Uses | Browsers, RequireJS |
ES Modules | Uses | 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 filesimportβ 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.