CJS, AMD, UMD, ESM
About
CommonJS, ESM (ES Module) always get me confused. Let's take a look at what they are and how their syntaxes differ from each other.
CJS
CJS stands for 'CommonJS'.
If you've used Node.js at least once, you're probably familiar with CJS. That's because Node.js supports CJS module format.
CJS imports modules synchronously.
Modules can be imported from
node_modules
or local directories.CJS returns a copy of the imported module.
CJS won't work in the browser. It must be transpiled and bundled.
AMD
AMD stands for 'Asynchronous Module Definition'.
AMD imports modules asynchronously, as its name suggests.
AMD is made for front end. (when it was proposed) (while CJS is for back end)
AMD syntax is less intuitive than CJS.
Personally, I haven't seen one using this syntax.
UMD
UMD stands for 'Universal Module Definition'.
Works on front end and back end (hence, universal).
Unlike CJS / AMD, UMD is more like a pattern to configure several module systems.
UMD is usually used as a fallback module when using bundler like Rollup / Webpack.
ESM
ESM stands for 'ES Modules'.
The 'standard' module system of JavaScript.
Works in many modern browsers
It's the best of all - CJS-like simple syntax + AMD's asynchronous module import
Tree-shakeable (due to ES6's static module structure)
ESM allows bundlers to remove unnecessary code, allowing end result sites to have less codes to get loaded faster.
It can be called within an HTML.
Summary
ESM - simple syntax, asynchronous, and tree-shakeable. The best!
UMD - works everywhere, usually used as a fallback in case ESM doesn't work.
CJS - synchronous, good for back end.
AMD - asynchronous, good for front end.
Credits
All the credits go to:
Last updated