18 Oct 2023 ~ 2 min read

ESM V. CommonJS


🔎 CheatSheet

CommonJSESM
HistoryCommonJS modules “are the original way to package JavaScript code for Node.js” and have been supported since Node.js’s original release in 2009.ESM (ECMAScript Modules) “are the official standard format to package JavaScript code for reuse.” and were first introduced with ES2015 (ES6) in 2015.
Loading/ExecutionSynchronousAsynchronous
Unique characteristicsUses __filename, __dirname, and NODE_PATH variablesUses top-level await
Importsconst module = require('file-path');import defaultThing, { namedThing } from 'file-path';
Exportsmodule.exports=defaultThing, exports=readOnlyThing, module.exports.name=namedThing, exports.name=readOnlyNamedThingexport default defaultThing, export namedThing
package.json - “type”"type": "commonjs""type": "module"
package.json - entry point"entry": "index.js""exports": "./index.js"
File Extensions.js & .ts by default or if "type": "commonjs" or commonjs syntax is detected. Also .cjs, .cts.js & .ts if "type": "module" or ESM syntax detected. Also .mjs, .mts
Runtime SupportAll Node.js versionsNode.js V12 or higher
Strict ModeRequires use strict at top of fileUses strict mode by default
Thisthis = exportsthis = undefined

📚 Resources