7. CommonJS vs ES Modules (require vs import)

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.

CommonJS vs ES Modules

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 ⚡🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال