search

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

Comments:
Likes:
Shares:
Best Division

Best Division  @bestdivision

Published On - Last Updated -

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

CJS, UMD, AMD, and ESM are all different module systems used in JavaScript for organizing and sharing code in a more maintainable and scalable way.

1: CommonJS (CJS): CommonJS is a module system used in server-side JavaScript environments such as Node.js. It uses the module.exports and require() statements to define and import modules. Here is an example of how to define a module in CommonJS:

// myModule.js
module.exports = {
  greet: function() {
    console.log('Hello, world!');
  }
};

// index.js
const myModule = require('./myModule');
myModule.greet();

2: Universal Module Definition (UMD): UMD is a pattern for writing modular JavaScript code that works in both CommonJS and AMD environments. It aims to provide a way to write code that can be used in different environments without having to worry about the module format. Here is an example of a UMD module:

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['dependency'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require('dependency'));
  } else {
    // Browser globals (root is window)
    root.returnExports = factory(root.dependency);
  }
}(this, function (dependency) {
  // Methods
  function myModule() {
    console.log('Hello, world!');
  }

  // Exposed public methods
  return {
    myModule: myModule
  };
}));

3: Asynchronous Module Definition (AMD): AMD is a module system used in client-side JavaScript environments such as web browsers. It uses the define and require functions to define and import modules. Here is an example of how to define an AMD module:

define(['dependency'], function(dependency) {
  // Methods
  function myModule() {
    console.log('Hello, world!');
  }

  // Exposed public methods
  return {
    myModule: myModule
  };
});

4: ECMAScript Module (ESM): ESM is a new standard for writing modular JavaScript code. It is part of the ECMAScript specification and is supported in modern JavaScript environments such as Node.js and modern web browsers. It uses the import and export statements to define and import modules. Here is an example of how to define an ESM module:

// myModule.js
export function greet() {
  console.log('Hello, world!');
}

// index.js
import { greet } from './myModule.js';
greet();
Similar Blogs
0 Commentssort Sort By

@abcd 1 days ago

Aquí los que apoyamos a Los del limit desde sus inicios..

dislike
reply
sdfsdf