(Organize code into reusable and maintainable blocks with ES Modules)
Modules allow you to split your code into multiple files, keeping your codebase clean and organized. Each file can export variables, functions, or classes, and other files can import them.
This modular approach helps in:
To use modules in the browser, add type="module" in your <script> tag:
<script type="module" src="main.js"></script>You can export functions, variables, or classes from a module file.
// file: mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;You can also export after declaration:
const multiply = (a, b) => a * b;
export { multiply };// file: main.js
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2You can also alias the import:
import { add as sum } from './mathUtils.js';A module can have one default export.
// file: greet.js
export default function greet(name) {
console.log(`Hello, ${name}`);
}Importing a default export:
import greet from './greet.js';
greet('Alice'); // Hello, Alice// file: utils.js
export const log = msg => console.log(msg);
export default function sayHi() {
console.log("Hi!");
}import sayHi, { log } from './utils.js';You can re-export everything from another module:
// file: allUtils.js
export * from './mathUtils.js';// file: main.js
import * as math from './mathUtils.js';
console.log(math.add(2, 3)); // 5You don't need "use strict" in module files — they run in strict mode automatically.
Variables in modules are local to that module. They don’t leak into the global scope.
Live Server in VS Code or http-server) — otherwise, you may get CORS or loading errors..mjs extension or set "type": "module" in package.json to use ES modules.export and import to share code across files.math.js file and export add, subtract, multiply, divide.main.js file that imports and uses all those functions.greet() function in a separate module.import * as syntax to bring all exports into one object.