Node.js Modules: Understanding CommonJS and ES Modules
What are Modules?
Modules are reusable pieces of code that help organize your application into manageable, maintainable pieces. Node.js has a powerful module system that allows you to break down your code into smaller, focused files.
CommonJS vs ES Modules
- CommonJS: The original module system in Node.js
- ES Modules: The modern standard for JavaScript modules
CommonJS Modules
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract
};
// app.js
const { add, subtract } = require('./math');
console.log(add(5, 3)); // 8
ES Modules
// math.mjs
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.mjs
import { add, subtract } from './math.mjs';
console.log(add(5, 3)); // 8
Best Practices
- Keep modules small and focused
- Use descriptive names
- Document your modules
- Avoid circular dependencies
Conclusion
Understanding modules is essential for building scalable Node.js applications. Choose the module system that best fits your project requirements.