Understanding CJS, EMS and UMD

Rajat Saxena

July 9, 2023

When JavaScript was created some twenty years ago, modularity was not something that was supported out of the box. 

When people started building complex and bigger project with JavaScript, they started craving for a way to modularise their code by breaking down their code into various files or modules. That requirement gave birth to all these module systems which we are going to learn about in this post.

Following are major module systems in the JavaScript ecosystem.

Let's learn about each of these in detail.

CJS

If you have used Node.js, you probably have seen this module system in action. Although Node.js' implementation is only inspired by CJS, it resembles CJS specs quite a lot. Using this system, you can export symbols from a file (module) using the exports object. In order to import symbols from other modules, you need to require them in your code. 

CJS is synchronous in nature, which means that execution is blocked until a module is imported successfully.

AMD

AMD was created as a result of a disagreement between a few members of the CJS developer group. The members who were not happy with the direction CJS was heading in parted ways and created AMD.

AMD embraces browsers' way of working with modules hence it support asynchronicity. AMD uses define keyword and a factory function to provide the module loading functionality.

Dojo and RequireJS are two frameworks which support outputting AMD compatible code. AMD supports loader plugins which means you can load different types of resources as dependencies.

ESM

ESM is developed by ECMA, the committee behind ECMAScript which is the specification JavaScript is based on. You use export keyword to export symbols from a module and import for importing symbols into the module from other modules. Since ESM is a part of the specification, it is natively supported by browsers (not all of them at the time of this writing) and Node.js.

The code using ESM is tree-shakable i.e. unused code can be eliminated by the static analysers and will not be included in the final build.

The only downside of using ESM I was able to find out was that it is not yet supported by all the browsers out there.

That's it for this comparison. I hope I was able to explain the why and how of these module systems. If you have queries regarding this post, come ask in our discord group.

Become that "Pro" full stack developer at your job

Receive our best tips, tutorials, videos and interview questions right in your inbox, weekly. Grow as a full stack dev. A little, every week. 🚀