⚖️ES vs CommonJS

JSmodule ⟩ ES vs CommonJS

(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           ✅           ✅
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 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.)

Last updated