[Javascript] CJS vs ESM
The key differences between CommonJS (CJS) and ECMAScript Modules (ESM) come down to their execution model.
- CommonJS (CJS)
- Synchronous: Each
require()
call blocks execution until the module is loaded. - Cached: Modules are loaded and cached once (so repeated
require()
calls return the same instance).
- Synchronous: Each
- ECMAScript Modules (ESM)
- Asynchronous & Static: The browser and Node.js can analyze dependencies before execution.
- Tree-Shaking Friendly: Unused exports can be removed by bundlers, making code size smaller.
For modren web developmenet, ESM is recommended.
Reason is when we use ESM, we have to declare file dependiences on top of the code
import fn from "./1js"
import wef from "./2js"
It's easier to do some optimiztion (tree shaking...).
CJS: Due to execution is runtime, it is hard to analysis the dependiences.
if (xxx) {
const fn = require("./1js")
} else {
const wef = require("./2js")
}