Konubinix' opinionated web of thoughts

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

Fleeting

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

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 }

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

node uses CJS module format

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

import from a library node_modules or local dir. Either by const myLocalModule = require(’./some/local/file.js’) or var React = require(‘react’); works.

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

give you a copy of the imported object.

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

CJS will not work in the browser. It will have to be transpiled and bundled.

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

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

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

AMD is made for frontend (when it was proposed) (while CJS backend).

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

UMD stands for Universal Module Definition

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

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;

}));

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

Works on front and back end (hence the name universal)

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

UMD is usually used as a fallback module when using bundler like Rollup/ Webpack

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

ESM stands for ES Modules

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

Javascript’s proposal to implement a standard module system

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

import React from ‘react’;

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

import {foo, bar} from ‘./myLib’;

export default function() { // your Function }; export const function1() {…}; export const function2() {…};

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

Works in many modern browsers

https://irian.to/blogs/what-are-cjs-amd-umd-and-esm-in-javascript/

Notes linking here