DevAcademy
LearnNode.jsModules: CommonJS vs ESM
BeginnerNode.js

Modules: CommonJS vs ESM

Node.js supports two module systems for organizing code across files — know how each works.

Reading Time

14 min

Lesson

Lesson 6 of 34

Two Module Systems

CommonJS (require/module.exports) is Node.js's original module system. ES Modules (import/export) is the standard JavaScript module system, also used in the browser. Node.js supports both, but a file uses one or the other, not a mix.

CommonJS

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

ES Modules

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Key Differences

AspectCommonJSES Modules
Import syntaxrequire()import
Export syntaxmodule.exportsexport
LoadingSynchronousCan be asynchronous
File extension needed on importOptionalRequired (./math.js, not ./math)

Telling Node.js Which System to Use

{
  "type": "module"
}
// In package.json — this makes .js files use ES Modules by default.
// Without it, .js files default to CommonJS.

Mixed File Extensions

Regardless of the "type" field, a .cjs file is always treated as CommonJS, and a .mjs file is always treated as ES Modules — useful when a project needs both in specific places.

Best Practice

For new projects, prefer ES Modules ("type": "module") — it is the standard, aligns with browser and frontend tooling conventions, and is where the JavaScript ecosystem is converging.

Interview Questions

Quick Quiz

1. What is the CommonJS equivalent of ES Modules' export?

2. What does "type": "module" in package.json do?

3. Is a file extension required when importing a local file with ES Modules?