What is the difference between CommonJS and ES modules
· Category: Node.js
Short answer
CommonJS uses require() and module.exports and loads modules synchronously. ES modules use import and export and support static analysis, tree shaking, and asynchronous loading.
Key differences
- Syntax: CommonJS uses
const x = require('x')andmodule.exports = x. ES modules useimport x from 'x'andexport default x. - Loading: CommonJS loads and executes modules synchronously at runtime. ES modules are parsed statically, enabling better optimization.
- Top-level await: ES modules support
awaitat the top level; CommonJS does not. - File extension: ES modules typically use
.mjsor"type": "module"in package.json. - Tree shaking: ES modules allow bundlers to remove unused code because imports are static.
When to use each
- Use CommonJS for legacy Node.js projects and when you need dynamic requires.
- Use ES modules for modern applications, frontend projects, and when you need static analysis and tree shaking.
- Node.js is moving toward ES modules as the standard for new projects.