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'.

// import
const someModule = require('./some-module.js')
var react = require('react') // this works too

// export
module.exports = function doSomething() {
  // do something
}
  • 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'.

define(['dep1', 'dep2'], function(dep1, dep2) {
  // Define the module value by returning a value
  return function() {}
})

// or

// Simplified CommonJS Wrapping (https://requirejs.org/docs/whyamd.html)
define(function(require) {
  var dep1 = require('dep1')
  dep2 = require('dep2')
  return function() {}
});
  • 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'.

(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 your own module implementation goes
  var Requester = {
    // ...
  }
  return Requester
}))
  • 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.

import React from 'react
import { foo, bar } from './my-lib'

// ...

export default function() {
  // your function
}
export const function1() {}
export const function2() {}
  • Works in many modern browsers

  • It's the best of all - CJS-like simple syntax + AMD's asynchronous module import

  • 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