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
// 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 requiredKey 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
| CommonJS | ES modules | |
|---|---|---|
| Enable with | default | "type": "module" or .mjs |
| Import syntax | require() | import |
| Loading | synchronous | asynchronous |
| __dirname | available | not available |
| Top-level await | no | yes |
| File extension in imports | optional | required 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.
