Modules are a fundamental building block of modern JavaScript applications. ES6 modules allow you to break your code into smaller, reusable pieces that can be easily maintained, tested, and debugged.
Imagine working on a large-scale project where all code is written in a single fileāthis would be a nightmare to manage! ES6 modules provide a way to **split code into multiple files** while keeping it organized and maintainable. With modules, you can:
export defaultThe export default statement allows you to export a **single** item from a file.
// wallet.js
export default class Wallet {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
}
When importing a default export, you can name it anything:
// main.js
import Money from './wallet.js';
const myWallet = new Money(100);
myWallet.deposit(50);
console.log(myWallet.balance); // 150
Instead of using export default, you can export multiple items:
// utilities.js
export function greet(name) {
return `Hello, ${name}!`;
}
export const PI = 3.14159;
When importing named exports, you must use **curly braces**:
// main.js
import { greet, PI } from './utilities.js';
console.log(greet("Alice")); // Hello, Alice!
console.log(PI); // 3.14159
You can rename imports using the as keyword:
import { greet as sayHello } from './utilities.js';
console.log(sayHello("Bob")); // Hello, Bob!
To use ES6 modules in an HTML file, specify type="module" in the <script> tag:
<script type="module" src="./app.js"></script>
Follow these steps to create a simple button-based game using ES6 modules.
index.html File
<html>
<head>
<meta charset="UTF-8">
<title>Simple Game</title>
</head>
<body>
<button id="button">Start Game</button>
<div id="message"></div>
<script type="module" src="./program.js"></script>
</body>
</html>
game.js Module
// game.js
export class Game {
constructor() {
this.message = "Do you want to play a game?";
}
start() {
document.getElementById('button').addEventListener('click', () => {
document.getElementById('message').innerText = this.message;
});
}
}
program.js File
// program.js
import { Game } from './game.js';
window.addEventListener('DOMContentLoaded', () => {
const game = new Game();
game.start();
});
Run a simple HTTP server to serve your files:
python3 -m http.server
Open your browser and navigate to http://localhost:8000 to see your game in action!
import and export instead of CommonJS's require and module.exports.export default for a **single** export per file.export { item }) when exporting **multiple** items.as to avoid naming conflicts.type="module" when including ES6 modules in an HTML file.Mastering ES6 modules will significantly improve how you structure your JavaScript projects. Whether you're working in the **browser** or **Node.js**, modularizing your code makes it more readable, scalable, and maintainable.