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
| Aspect | CommonJS | ES Modules |
|---|---|---|
| Import syntax | require() | import |
| Export syntax | module.exports | export |
| Loading | Synchronous | Can be asynchronous |
| File extension needed on import | Optional | Required (./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.