What is CJS, AMD, UMD, and ESM modules in JavaScript

☕️ 2 min read

CommonJS (CJS)

It’s commonly used in NodeJS and looks like the following example:

// import
const foo = require('./foo');

// export
module.exports = function foo(bar) {
  // your code
}
  • CJS imports module synchronously;
  • You can import from local or external node_modules like the following:
// local import
const localModule = require('./my-path/local-file.js');

// external import
const React = require('react');
  • When import via CJS, it will return a copy of the imported object;
  • CJS won’t work in the browser. It needs to be transpiled and bundled;

Asynchronous Module Definition (AMD)

Sample of how this module definition works i.e:

define(['firstDep', 'secondDep'], function (firstDep, secondDep) {
  // Define the module value by returning a value
  return function () {};
});

or the simplified CJS Wrapping way i.e:

define(function (require) {
  var firstDep = require('firstDep'),
      secondDep = require('secondDep');
  return function () {};
});
  • It imports modules asynchronously like the name says;
  • AMD went made by frontend (in the initial proposal) (while CJS for backend NodeJS);
  • It has a less intuitive syntax than CJS;

Universal Module Definition (UMD)

A short sample of how UMD works i.e:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['react', 'lodash'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('react'), require('lodash'));
    } else {
        root.Requester = factory(root.React, root._);
    }
}(this, function (React, _) {
    // this is where your module implementation will appear

    var Requester = {
        /// ...
    };

    return Requester;
}));
  • Works in frontend and backend;
  • Unlike the CJS or AMD, UMD is more like a pattern to configure several module systems;
  • UMD is commonly used as a fallback module when using module bundlers like Webpack or Rollup;

ES Modules (ESM)

It’s a proposal to implement a standard module system.

A sample example of ESM i.e:

import React from 'react';

or

import { myUtil, myCalc } from './myFile';

export default function () {
    // your function code
}

export const sum() {}
export const mult() {}
<script type="module">
import { myFunc } from './myLib';

myFunc();
</script>
  • ESM allows bundlers like Rollup to remove unused code, avoiding projects to ship deadcodes;

Note: It won’t work 100% of all browsers yet.

References