📦 JavaScript Modules – In Depth
JavaScript modules allow you to break your code into separate files for better maintainability and reusability.
Modern JS (ES6+) supports import
and export
syntax for working with modules.
✅ Named Exports
Export multiple things from one file using export
:
// utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// main.js
import { add, multiply } from './utils.js';
console.log(add(2, 3));
📌 Default Exports
Use export default
when only one main export is needed:
// greet.js
export default function greet(name) {
return `Hello, ${name}`;
}
// main.js
import greet from './greet.js';
console.log(greet("Alice"));
🔁 Combining Named and Default Exports
// mix.js
export const name = "JS Learner";
export default function sayHi() {
console.log("Hi!");
}
// main.js
import sayHi, { name } from './mix.js';
🌐 Using Modules in the Browser
Add type="module"
to your script tag:
<script type="module" src="main.js"></script>
🛠️ Module File Rules
- Use the
.js
extension when importing - Modules run in strict mode automatically
- Each module has its own scope
🚫 Common Errors
Uncaught SyntaxError: Cannot use import statement outside a module
– Fix: usetype="module"
- Missing file extension in import path
- Wrong file location or relative path
✅ Next Tip: Organize related functions and components into modules for cleaner, reusable code!