Modules
Why modules?
Section titled “Why modules?”Modules allow splitting a program into multiple reusable files.
➡ This makes code clearer, better organized, and easier to maintain.
Without modules, all code would be in one file, risking variable or function name conflicts.
Exporting a module
Section titled “Exporting a module”A file can export its functions, variables, or classes to make them available elsewhere.
export function add(a, b) { return a + b;}
export const PI = 3.14;
Importing a module
Section titled “Importing a module”Another file can then import what it needs.
import { add, PI } from "./math.js";
console.log(add(2, 3)); // 5console.log(PI); // 3.14
Use curly braces
{ }
to import named exports.
Default export
Section titled “Default export”A file can also have one default export.
In that case, you can import it with any name.
export default function greet(name) { return `Hello ${name}`;}
// main.jsimport greet from "./utils.js";
console.log(greet("Alice")); // Hello Alice
Named export vs default export
Section titled “Named export vs default export”Type | Declaration | Import |
---|---|---|
Named export | export function add() {} | import { add } from "./file.js" |
Default export | export default function greet() | import greet from "./file.js" |
Modules in Node.js
Section titled “Modules in Node.js”Before ES6 modules, Node.js used CommonJS:
// CommonJS (old)const fs = require("fs");
// ES6 (modern)import fs from "fs";
Today, Node.js supports ES6 modules (with the .mjs
extension or "type": "module"
in package.json).
Best practices
Section titled “Best practices”- Prefer named exports for clarity and flexibility.
- Use a default export only if the module provides a single main feature.
- Organize modules by topic or domain (e.g.,
math.js
,user.js
,api.js
). - Always include the
.js
extension in imports when targeting modern browsers.