In JavaScript, modules are a way to organize and encapsulate code into reusable units. Each module typically represents a specific functionality or feature in your application. By using modules, you can keep your code organized, improve maintainability, and avoid polluting the global namespace.
Why use Modules?
CommonJS is a standard used by Node.js to define how modules work. CommonJS modules allow you to export code from one file and import it into another.
Syntax:
module.exports.require().
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
const math = require('./math'); // Import the math module
const sum = math.add(5, 3);
const difference = math.subtract(5, 3);
console.log('Sum:', sum); // Output: Sum: 8
console.log('Difference:', difference); // Output: Difference: 2
Explanation: In math.js, we export the functions add and subtract by attaching them to module.exports. In app.js, we use require('./math') to import the math module and call its functions.
Output:
ES Modules (ECMAScript modules) are the modern standard for handling modules in JavaScript. ES modules are supported in modern browsers and JavaScript environments (like Node.js with proper configuration). They provide a more declarative approach to importing and exporting code.
Syntax:
export.import.
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
import { add, subtract } from './math.mjs'; // Import functions from math.mjs
const sum = add(5, 3);
const difference = subtract(5, 3);
console.log('Sum:', sum); // Output: Sum: 8
console.log('Difference:', difference); // Output: Difference: 2
Explanation: In math.mjs, we export the functions add and subtract using the export keyword. In app.mjs, we use the import keyword to import those functions.
Output:
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax for Export | module.exports = ... |
export and export default |
| Syntax for Import | require('...') |
import ... from '...' |
| Dynamic Import | No built-in dynamic import | Supports dynamic import() |
| Module Loading | Synchronously | Synchronously or Asynchronously |
| Use Case | Commonly used in Node.js | Commonly used in browsers, modern JavaScript environments |
To use ES Modules in Node.js, you need to use the .mjs file extension or specify "type": "module" in your package.json.
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
import { add, subtract } from './math.mjs';
console.log(add(3, 2)); // Output: 5
console.log(subtract(5, 2)); // Output: 3
Explanation: In math.mjs, we export the functions add and subtract. In app.mjs, we import and use those functions.
Output: