⚖️ES vs CommonJS
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
(Node.js)
ES modules can import
ES or CommonJS module exports.
CommonJS modules can only require
CommonJS module exports.
// (package.json in Node.js)
"type": "module" // ES module
"type": "commonjs" // CommonJS module (⭐️ default)
ES export CommonJS export
-------------------------------------------------
ES import ✅ ✅
module path name
const obj = require(`./${name}`); // require: can be dynamic
import {obj} from './module.js'; // import: must be string literal
file name extension
// require: can leave out .js when importing a local module.
require("./module") // ✅ works
// import: won't work without .js
import module from "./module" // ❌ won't work
import module from "./module.js" // ✅ works
execution order
require
(expression) - runs inline, after the code above it.
import
(statement) - runs before the rest of the script.
(note: import expressions can be dynamic.)
.js
"type":"module" -> ES module.
"type":"commonjs" -> CommonJS module.
can only use ES import
/ export
.
// (in Node.js) "type": "module"
import {str} from './es.mjs'; // .mjs - es module
import {obj} from './commonjs.cjs'; // .cjs - commonjs module