In Node.js, there are two ways to work with modules: CommonJS and ES Modules. Understanding the difference between them is important for writing modern JavaScript applications.
In this article, you will learn how require and import work and when to use each.
Comparison between require() and import in Node.js
1. What is CommonJS?
CommonJS is the default module system in Node.js. It uses require() and module.exports.
// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
// app.js
const add = require("./math");
console.log(add(5, 3));
2. What are ES Modules?
ES Modules are modern JavaScript modules using import and export.
Note: Warning: To load an ES module, set "type": "module" in the package.json
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./math.js";
console.log(add(5, 3));
3. Key Differences
| Feature | CommonJS | ES Modules |
|---|---|---|
| Syntax | require() | import |
| Export | module.exports | export |
| Loading | Synchronous | Asynchronous |
Use ES Modules for new projects and CommonJS for older ones.
Conclusion
Now you understand the difference between require and import.
Your Node.js journey is getting modern ⚡🚀
Tags
NodeJS