ES Modules: All You Need To Know
ESM and CommonJS are Javascript’s module systems. Let’s understand how they compare and when to choose which system.
ES Modules (or short: ESM) and CommonJS (or short: CJS) are the two module systems in Javascript that are actively being used. Module Systems allow us to share and reuse code easily. For example, we can write a module for image compression which can then be distributed via npmjs.com and used by developers around the world.
What is CommonJS?
CommonJS was introduced as the default module system for Node.js. Since this was way before ES Modules were released, most of the tooling and packages you find on npmjs.com and yarnpkg.com were initially written in CommonJS.
In Node, each file is treated as a separate module. You can import and export with the following CommonJS syntax:
While Node.js has been using the CommonJS standard for years, the browser never had a module system, as every major decision such as a module system must be first standardized by ECMAScript and then implemented by the browser.