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

Originally written by Igor Irianto

Translator:!

Because this question is often asked in interviews, it has been labeled “Interview speaking”.

Initially, Javascript had no way to import/export modules, which was a headache. Imagine writing an application with just one file — it’s a nightmare!

Then, a lot of people smarter than ME tried to modularize Javascript. Among them are CJS, AMD, UMD and ESM. You’ve probably heard of some of these methods (there are others, but these are more generic).

I’ll introduce them: their syntax, purpose, and basic behavior. My goal is to help readers recognize them when they see them

CJS

CJS stands for CommonJS. We often use it this way:

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

// exporting
module.exports = function doSomething(n) {
  // do something
}
Copy the code
  • A lot of people can learn fromNodeInstant recognitionCJSSyntax. This is becauseNodeIs the use ofCJSThe modulethe
  • CJSIs a synchronous import module
  • You can start yournode_modulesTo import a library or file from a local directory. Such asconst myLocalModule = require('./some/local/file.js')orvar React = require('react');, can work
  • whenCJSWhen you import, it will give you a copy of the imported object
  • CJSDoes not work in a browser. It must be transformed and packaged

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 () {};
});
Copy the code

or

// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.html
define(function (require) {
    var dep1 = require('dep1'),
        dep2 = require('dep2');
    return function () {};
});
Copy the code
  • AMDIs asynchronous (asynchronously) importing the module (hence the name)
  • When it was first proposed,AMDIs for the front end (andCJSIs the back-end)
  • AMDIs not as grammatical asCJSIntuitive. I thinkAMDCJSThe opposite

UMD

UMD stands for Universal Module Definition. Here’s what it might 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;
}));
Copy the code
  • Works on both the front end and back end (hence the name “universal”)
  • withCJSAMD Different, UMDMore like a pattern for configuring a multi-module system.hereMore patterns can be found
  • When usingRollup/WebpackOr something like that,UMDUsually used as a backup module

ESM

ESM stands for ES module. This is Javascript proposed to implement a standard module system scheme. I’m sure many of you have seen this:

import React from 'react';
Copy the code

Or more

import {foo, bar} from './myLib'; .export default function() {
  // your Function
};
export const function1(){... };export const function2(){... };Copy the code
  • It is available in many modern browsers
  • It has the advantages of two things: it hasCJSSimple syntax andAMDThe asynchronous
  • Thanks to theES6 的Static module structure, can be carried out Tree Shaking
  • ESMAllow likeRollupA packer like this,Remove unnecessary codeReduce the number of code packages for faster loading
  • Can be found inHTML, as long as the following
<script type="module">
  import {func1} from 'my-lib';

  func1();
</script>
Copy the code

But not all browsers support it (source)

conclusion

  • Due to theESMWith its simple syntax, asynchronous nature, and tree shakability, it is the best modular solution
  • UMDYou see it everywhere, usually inESMUse as a backup if it doesn’t work
  • CJSIt is synchronous and suitable for the back end
  • AMDAsynchronous, suitable for the front end

Thanks for reading, developers! In the future, I plan to discuss each module in depth, especially the ESM, because it contains so many great things. Stay tuned!

Please let me know if you notice any mistakes.

reference

  • basic js modules
  • CJS in nodejs
  • CJs-ESM comparison
  • On inventing JS module formats and script loaders
  • Why use AMD
  • es6 modules browser compatibility
  • Reduce JS payloads with tree-shaking
  • JS modules – static structure
  • ESM in browsers
  • ES Modules deep dive – cartoon
  • Reasons to use ESM