JavaScript modules
JavaScript modules let you split code into separate files and share functionality between them. There are two main systems for modules in JavaScript:
- CommonJS: used by Node.js for many years.
- ES modules (often just called "modules" or "module JS"): the modern standard supported by browsers and newer Node.js versions.
CommonJS
CommonJS uses require() to load code and module.exports or exports to share values.
Example:
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// main.js
const { add } = require("./math");
console.log(add(3, 4)); // 7
CommonJS loads modules synchronously and works well in Node.js. It is the older module system and still common in many Node projects.
ES modules (module JS)
ES modules use import and export syntax. This is the newer, standard way to write modules in JavaScript.
Example:
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from "./math.js";
console.log(add(3, 4)); // 7
ES modules can also export a default value:
// logger.js
export default function log(message) {
console.log(message);
}
// main.js
import log from "./logger.js";
log("Hello modules");
Which one to use?
- Use CommonJS when you are working with older Node.js projects or tools that still expect
require(). - Use ES modules for modern browser code and newer Node.js projects. They are the standard and work naturally with
import/export.
Both systems let you keep code organized by splitting it into smaller files and reusing functionality.