Modules
A module is a file that exports functions, objects or values so that other files can import them. This is how you organize code into small, reusable pieces.
ES Modules (modern standard)
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// app.js
import { add, PI } from "./math.js";
console.log(add(2, 3), PI);
There is also the default export:
// greeting.js
export default function (name) {
return `Hello, ${name}`;
}
// app.js
import greeting from "./greeting.js";
CommonJS (classic Node style)
Before ES Modules, Node used require and module.exports:
// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require("./math.js");
Today it is recommended to use ES Modules (
import/export), which are the standard both in the browser and in modern Node.
Examples
A 'module' as an exported object
const math = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
};
console.log(math.add(10, 5));
console.log(math.subtract(10, 5));