When to Use CommonJS in Modern Projects
You'll learn when CommonJS still makes sense and why ES modules are now the recommended standard.
The State of Affairs
CommonJS was the original module system for Node.js, but ES modules (ESM) are now the official JavaScript standard supported in both browsers and Node.js. CommonJS persists primarily in legacy code, not new development.
Where CommonJS Still Appears
You'll encounter CommonJS in:
- Legacy Node.js projects built before ES modules became stable
- Older npm packages that haven't been updated
- Build tools and configuration files (like webpack.config.js) that may still use
require() - Projects maintaining backward compatibility with Node.js versions before v12
Why ES Modules Are Preferred for New Projects
ES modules offer significant advantages:
- Universal standard: Works in browsers AND Node.js
- Static analysis: Enables tree shaking and better bundling
- Async loading: Supports modern loading patterns
- Official spec: Part of the JavaScript language itself
Think of it like transitioning from old measurements to the metric system—CommonJS works, but ES modules are the universal standard everyone's moving toward.
The Modern Approach
For new projects: Use ES modules (.mjs or "type": "module" in package.json). For existing projects: Maintain CommonJS if migration isn't worth the effort. For libraries: Consider dual publishing to support both systems.
Key Takeaway: CommonJS is primarily for maintaining legacy code—ES modules are the modern standard for new JavaScript projects, offering better tooling support and cross-platform compatibility.