Skip to content

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.


A file can export its functions, variables, or classes to make them available elsewhere.

math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14;

Another file can then import what it needs.

main.js
import { add, PI } from "./math.js";
console.log(add(2, 3)); // 5
console.log(PI); // 3.14

Use curly braces { } to import named exports.


A file can also have one default export.
In that case, you can import it with any name.

utils.js
export default function greet(name) {
return `Hello ${name}`;
}
// main.js
import greet from "./utils.js";
console.log(greet("Alice")); // Hello Alice

TypeDeclarationImport
Named exportexport function add() {}import { add } from "./file.js"
Default exportexport default function greet()import greet from "./file.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).


  • 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.