JavaScript Modules
JavaScript modules are self contained pieces of code that can be reused with other JavaScript modules or in our JavaScript projects. There are mainly 4 different ways we can pack JavaScript code into modules - They are ESM, CJS, AMD and UMD
ESM - ECMAScript modules are the official standard format to package JavaScript code for reuse. So, if you are starting a new project or you get some time to refactor your existing project's code, start with ESM.
As of today ESM support is avaialble across all major browsers (Check Can I use ESM?) as well as in Node.js starting version 8.5.0
ESM vs CJS vs AMD vs UMD
ESM (ECMAScript Modules)
- Official standard format
- Loads modules asynchronously
- Best for both Node.js (server-side) as well as in the browsers (client-side)
CJS (Common JS)
- Introduced for use in Node.js and mainly used on server-side
- Loads modules synchronously
- `module.exports` for exporting and `require` for synchronous loading
- Node.js by default supports this and no external library is needed
AMD (Asynchronous Module Definition)
- Used to support module system in the browsers (client-side)
- Loads modules asynchronously
- Users `define` and `require`
- Node.js doesn't support AMD natively. We need to use external libraries to support the same.
UMD (Universal Module Definition)
- Used to support both on server-side as well as on client-side
- Loads modules asynchronously as well as synchronously
- UMD allows to use libraries that are dessigned to work in both browser and server-side environments