What’s the difference between CommonJS and ECMAScript Modules (ESM)?
In a nutshell
Both CommonJS and ECMAScript modules (ESM) are mechanisms that let you split your JavaScript applications into modules.
CommonJS was originally developed for server-side JavaScript (mainly for Node.js) before ECCMAScript modules were introduced in ES6 (EcmaScript 2015).
Nowadays, both Node.js (from v12 onwards) and major browsers support ESM. A lot of projects on NPM are written in CommonJS so CommonJS is likely to be around for a while but ESM will probably become more common with time.
CommonJS
Syntax
// Import from module
const module = require('module-name')
const { export1, export2 } = require('module-name')
// Export from module
module.exports = something // or
export.something = something
Dynamic imports
You can dynamically require
modules inside conditions and functions during runtime.
Synchronous loading
Modules are loaded synchronously by default which works well in server environments like Node.js, but isn’t ideal for the web. On the web, you’d want to only load the modules needed for a particular page so asynchronous loading is ideal.
Example
ECMAScript modules (ESM)
Syntax
// Import from module
import module from 'module' // or
import { export1, export2 } from 'module-name'
// Export from module
export default something // or
export const something
Dynamic imports
You can’t import
a module dynamically but you can use the import()
function that will return a promise that resolves when the module is successfully loaded.
Asynchronous loading
ESM modules can be asynchronously loaded, making them ideal for the web where modules can be fetched via HTTP.
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment