DEV Community

Igor Irianto
Igor Irianto

Posted on • Edited on • Originally published at irian.to

What the heck are CJS, AMD, UMD, and ESM in Javascript?

In the beginning, Javascript did not have a way to import/export modules. This is a problem. Imagine writing your app in just one file - it would be nightmarish!

Then, people much, much smarter than me attempted to add modularity to Javascript. Some of them are CJS, AMD, UMD, and ESM. You may have heard some of them (there are other methods, but these are the big players).

I will cover high-level information: syntax, purpose, and basic behaviors. My goal is to help readers recognize when they see them in the wild 💡.

CJS

CJS is short for CommonJS. Here is what it looks like:

//importing 
const doSomething = require('./doSomething.js'); 

//exporting
module.exports = function doSomething(n) {
  // do something
}
Enter fullscreen mode Exit fullscreen mode
  • Some of you may immediately recognize CJS syntax from node. That's because node uses CJS module format.
  • CJS imports module synchronously.
  • You can import from a library node_modules or local dir. Either by const myLocalModule = require('./some/local/file.js') or var React = require('react'); works.
  • When CJS imports, it will give you a copy of the imported object.
  • CJS will not work in the browser. It will have to be transpiled and bundled.

AMD

AMD stands for Asynchronous Module Definition. Here is a sample code:

define(['dep1', 'dep2'], function (dep1, dep2) {
    //Define the module value by returning a value.
    return function () {};
});
Enter fullscreen mode Exit fullscreen mode

or

// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.html
define(function (require) {
    var dep1 = require('dep1'),
        dep2 = require('dep2');
    return function () {};
});
Enter fullscreen mode Exit fullscreen mode
  • AMD imports modules asynchronously (hence the name).
  • AMD is made for frontend (when it was proposed) (while CJS backend).
  • AMD syntax is less intuitive than CJS. I think of AMD as the exact opposite sibling of CJS.

UMD

UMD stands for Universal Module Definition. Here is what it may look like (source):

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(["jquery", "underscore"], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require("jquery"), require("underscore"));
    } else {
        root.Requester = factory(root.$, root._);
    }
}(this, function ($, _) {
    // this is where I defined my module implementation

    var Requester = { // ... };

    return Requester;
}));
Enter fullscreen mode Exit fullscreen mode
  • Works on front and back end (hence the name universal).
  • Unlike CJS or AMD, UMD is more like a pattern to configure several module systems. Check here for more patterns.
  • UMD is usually used as a fallback module when using bundler like Rollup/ Webpack

ESM

ESM stands for ES Modules. It is Javascript's proposal to implement a standard module system. I am sure many of you have seen this:

import React from 'react';
Enter fullscreen mode Exit fullscreen mode

Other sightings in the wild:

import {foo, bar} from './myLib';

...

export default function() {
  // your Function
};
export const function1() {...};
export const function2() {...};
Enter fullscreen mode Exit fullscreen mode
<script type="module">
  import {func1} from 'my-lib';

  func1();
</script>
Enter fullscreen mode Exit fullscreen mode

This may not work 100% in all browsers yet (source).

Summary

  • ESM is the best module format thanks to its simple syntax, async nature, and tree-shakeability.
  • UMD works everywhere and usually used as a fallback in case ESM does not work
  • CJS is synchronous and good for back end.
  • AMD is asynchronous and good for front end.

Thanks for reading, devs! In the future, I plan to write in depth about each module, especially ESM because it is packed with many awesomeness. Stay tuned!

Let me know if you notice any errors.

Resources:

Latest comments (23)

Collapse
 
dasu_ae65e69f55387d2cbf53 profile image
Dasu

It was really help full , thanks

Collapse
 
masterinquestion profile image
MasterInQuestion • Edited

    Is writing everything in one file really necessarily nightmarish..?
    Haven't seen enough dependency hell and god-know-how..?
    Much the reason people disfavor GOTO spaghetti.

    Extreme invert. Excess amok.
    Insane decoupling is not applicable: things are by nature coupled, inseparable.
    Elements are each other coupled and constitute a blob of whole, much of unawarely implications.
    .
    Well realizing the underlying implementation is the only way to guarantee effectiveness and efficiency.

Collapse
 
artu_hnrq profile image
Arthur Henrique

I didn't know these definitions before this reading...
Thanks for the well wrote sharing, Igor!

Collapse
 
fakenickel profile image
FakeNickel

I count myself lucky enough to see the wonderful answer 4 years later here since 2019.

Thanks for the article you shared with us and the discussions indeed sovle my problem.

Collapse
 
digitalnaut profile image
Cybernaut

Still relevant in 2022 and really cleared things up for me 👏 Thank you!

Collapse
 
gpingfeng profile image
Gopal

Hello, may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
 
iggredible profile image
Igor Irianto

Sorry for the late reply, definitely!

Collapse
 
roser137 profile image
roser137

Do CJS imports copies the exported object? I think not. If you create an object in a module and export it using module.exports it is used for every import. Imports from other modules do not create new objects. They uses the same object.

Collapse
 
samwatts98 profile image
Sam Watts

Thanks for this explanation! Very concise, well written, and well compared. :)

Collapse
 
vadorequest profile image
Vadorequest

Another really good article, older, bug goes much more in-depth.

hacks.mozilla.org/2018/03/es-modul...

Collapse
 
iggredible profile image
Igor Irianto

This is another good article. Good suggestion!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.