Introduction
JavaScript modules allow you to split your code into separate files and import/export them.
Instead of having one huge script, modules create clean, reusable pieces of logic.
Modules are loaded using import and export.
1. Named Exports
// math.js
export function add(a, b) {
return a + b;
}
export const pi = 3.14;
2. Importing Named Exports
// main.js
import { add, pi } from "./math.js";
console.log(add(5, 3));
console.log(pi);
3. Default Export
Each module can have ONE default export.
// user.js
export default function getUser() {
return { name: "Kaloyan", age: 12 };
}
4. Importing Default Export
import getUser from "./user.js";
console.log(getUser());
5. Mixing Default + Named Exports
// utils.js
export default "v1.0";
export function log(msg) {
console.log(msg);
}
// main.js
import version, { log } from "./utils.js";
log("Loaded version " + version);
6. Renaming Exports (aliasing)
import { add as plus } from "./math.js";
plus(10, 20);
7. Exporting All Under a Namespace
// main.js
import * as Tools from "./math.js";
console.log(Tools.add(3, 7));
console.log(Tools.pi);
8. Exporting Inline
export const brand = "CodeTweakrs";
export function greet(name) {
return `Hello, ${name}`;
}
9. Module Scripts in HTML
Modules load with strict mode and support import/export directly in browsers.
10. Importing from URLs
Useful for CDNs.
import _ from "https://cdn.jsdelivr.net/npm/lodash-es/lodash.js";
11. Dynamic Imports
Load modules only when needed (lazy loading).
const math = await import("./math.js");
console.log(math.add(2, 3));
12. When to Use Modules
- Large JS projects
- Organizing reusable functions
- Splitting UI components
- Reducing file size via lazy loading
- Cleaner and safer code structure
Summary
- Use
exportto share variables or functions - Use
importto include them in other files - Default exports = one per module
- Named exports = unlimited
- Modules isolate scope and avoid global pollution
- Dynamic imports boost performance