MyInternships.in

Node.js Basics

Node.js CommonJS vs ES Modules

Node supports two module systems. CommonJS uses require and module.exports and is the historical default. ES modules use import and export, are the JavaScript standard, and are the recommended choice for new projects.


What is CommonJS vs ES Modules in Node.js?

Node supports two module systems. CommonJS uses require and module.exports and is the historical default. ES modules use import and export, are the JavaScript standard, and are the recommended choice for new projects.

CommonJS vs ES Modules example

The same module in both systems
JavaScript
// CommonJS — math.js
function add(a, b) { return a + b; }
module.exports = { add };

const { add } = require('./math');

// ES modules — math.js
export function add(a, b) { return a + b; }
export default add;

import { add } from './math.js';   // extension required

Key points to remember

  • Set "type": "module" in package.json to make .js files ES modules.
  • ES modules can import CommonJS packages; the reverse needs a dynamic import().
  • Local ES module imports must include the .js extension.
  • Choose one style per project rather than mixing.

CommonJS vs ES modules

CommonJSES modules
Enable withdefault"type": "module" or .mjs
Import syntaxrequire()import
Loadingsynchronousasynchronous
__dirnameavailablenot available
Top-level awaitnoyes
File extension in importsoptionalrequired for local files

Common mistakes with CommonJS vs ES Modules

  • ERR_REQUIRE_ESM — using require on an ES-module-only package.
  • Omitting the file extension in an ES module import and getting ERR_MODULE_NOT_FOUND.
  • Using top-level await in a CommonJS file.

Node.js CommonJS vs ES Modules— Interview Questions & FAQs

Should I use require or import in Node.js?+

Use import in new projects — ES modules are the JavaScript standard, support top-level await, and match front-end code. Learn require too, because most existing tutorials and codebases use it.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships