CommonJS vs ESM
- Node.js course
- Beginner
- Lesson 5/116
- 5 min
Learn the difference between CommonJS (require) and ES modules.
CommonJS vs ESM
Node.js has two module systems: CommonJS (old) and ES modules (modern). ESM is recommended in Node.js 22.
In CommonJS, you export with module.exports and import with require. In ESM, you use export and import.
Mixing the two in one project causes errors; you select ESM by setting "type": "module" in package.json. You may see CommonJS in old code, but use ESM in new code.
Which should you choose?
When starting a new project, choosing ESM is recommended. If you add "type": "module" to package.json, all your .js files are treated as ESM.
If you are maintaining an old project that uses require, staying with CommonJS may be the consistent choice. Still, prefer ESM for new additions.
Do not mix the two systems in the same file; it is confusing and leads to errors.
Practice Write an ESM import
Import the greet function from ./hello.js. Then call console.log with greet('World').
Starter code
// Import greet from ./hello.js
// Then call greet('World') and log itSample solution
import { greet } from "./hello.js";
console.log(greet("World"));Expected output
Hello, World
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Import with require
CommonJS: const fs = ____("fs");
CommonJS: const fs = require("fs");
Explanation: CommonJS uses require.
2 What does "type": "module" do?
- Deletes all .js files
- Recognizes only .mjs files
- Disables npm commands
- Treats all .js files as ESM Correct answer
Explanation: type: module treats .js files as ESM.
3 Match the module systems
| Term | Meaning |
|---|---|
require |
CommonJS import |
import |
ESM import |
module.exports |
CommonJS export |
export |
ESM export |