21. Modular JavaScript & ES Modules
Why Modules Matter
As JavaScript apps grow, keeping all code in a single file becomes messy and hard to maintain. Modules allow you to split code into logical pieces, making it reusable, easier to read, and simpler to debug.
Exporting from a Module
You can export variables, functions, or classes from a file so they can be used elsewhere. There are two main ways: named exports and default exports.
// mathUtils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// Or default export
export default function subtract(a, b) {
return a - b;
}Importing Modules
Once you export code from a module, you can import it in another file to use its functions or variables.
// main.js
import subtract, { add, multiply } from './mathUtils.js';
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
console.log(subtract(10, 4));// 6Named vs Default Exports
Named exports allow multiple exports per file, each imported using the same name. Default exports let a file export one main thing, imported without curly braces.
// Named export example
export const pi = 3.1415;
export const e = 2.718;
// Importing named exports
import { pi, e } from './constants.js';
// Default export example
export default class Circle {
constructor(radius) {
this.radius = radius;
}
}
// Importing default
import Circle from './Circle.js';Dynamic Imports
ES Modules also support dynamic imports with the `import()` function. This allows you to load a module only when it’s needed, improving performance.
async function loadMathUtils() {
const math = await import('./mathUtils.js');
console.log(math.add(5, 7));
}
loadMathUtils();Using Modules in Browsers
To use ES Modules in the browser, include `type="module"` in your `<script>` tag.
<script type="module" src="main.js"></script>Common Pitfalls
- Browser must support modules or you need a bundler like Webpack or Vite.
- Default and named exports can’t be mixed incorrectly.
- File paths are relative; always include extensions like `.js` in browsers.
Mini Challenge
1. Create a `stringUtils.js` module that exports functions to `capitalize`, `reverse`, and `countVowels` of a string. 2. In `main.js`, import your module and demonstrate each function. 3. Try a dynamic import to load `stringUtils.js` only when a button is clicked.