- 
                Notifications
    
You must be signed in to change notification settings  - Fork 16
 
Research: ES Modules vs CommonJS
        Matěj Chalk edited this page Aug 18, 2023 
        ·
        12 revisions
      
    We've decided on using JavaScript config files. But this presents the problem whether to support both CommonJS and ES Modules, and how that can be implemented and tested.
| CommonJS | ES Modules | |
|---|---|---|
| ecosystem trends | older and more widely supported | Node 13+ and some newer packages | 
| import/export syntax | 
require() and module.exports = 
 | 
import and export, also dynamic import()
 | 
| explicit file extensions | 
.cjs/.cts
 | 
.mjs/.mts
 | 
implicit file extensions (.js) | 
if "type" not specified or set to "commonjs" in package.json
 | 
if "type": "module" in package.json
 | 
package.json's "exports" (separate entry points) | 
"require": "<path/to/cjs/script>" | 
"import": "<path/to/esm/script>" | 
| interoperability | ESM->CJS: must use async import()
 | 
CJS->ESM: import ... from './foo.cjs'
 | 
- CommonJS (cjs) and Modules (esm): Import compatibility
 - TypeScript: ECMAScript Modules in Node.js
 - Jest: ECMAScript Modules
 
- some bundlers support multiple formats (tsup, Rollup)
- Nx has a Rollup plugin (@nx/rollup) 😍
 
 
- Jest runs as CommonJS, support for ESM experimental
 - Vitest runs as ESM (also an Nx plugin 😍)