⚖️ES vs CommonJS
(Node.js)
ES modules can
importES or CommonJS module exports.CommonJS modules can only
requireCommonJS module exports.
// (package.json in Node.js)
"type": "module" // ES module
"type": "commonjs" // CommonJS module (⭐️ default)
ES export CommonJS export
-------------------------------------------------
ES import ✅ ✅
CommonJS require ❌ ✅
-------------------------------------------------
⭐️ looks like CommonJS "module.exports" is a better choice❓ module path name
const obj = require(`./${name}`); // require: can be dynamic
import {obj} from './module.js'; // import: must be string literalfile 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" // ✅ worksexecution 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.)
(Node.js) in an ES module (.mjs / .js of "type":"module"):
can only use
import/export.can import CommonJS exports.
cannot use
require.
// (in Node.js) "type": "module"
import {str} from './es.mjs'; // .mjs - es module
import {obj} from './commonjs.cjs'; // .cjs - commonjs module(Node.js) in an CommonJS module (.cjs / .js of "type":"commonjs"):
cannot use
requireto load an ES module.
(in browser)
cannot use
require.cannot import CommonJS exports.
can only use ES
import/export.
Last updated
Was this helpful?