Skip to main content

Javascript Modules: AMD, CommonJS, ES6 Modules

JavaScript modules are a way to structure and organize code in JavaScript, allowing for easier management of dependencies and code reuse.

Over the years, several module formats have emerged, each with its own set of features and use cases. Let's discuss the four you mentioned: AMD, CommonJS, RequireJS, and ES6 Modules.

Asynchronous Module Definition (AMD)

  • Primarily used in Browser environments
  • Modules are loaded asynchronous
  • Modules are loaded on-demand when needed, improving page load time

Example:

// module.js
define("myModule", function (require, exports, module) {
exports.sum = function (a, b) {
return a + b;
};
});
// app.js
require(["myModule"], function (myModule) {
myModule.sum();
});

CommonJS Modules (CJS)

  • CommonJS designed for server-side environments like Node.js
  • Uses synchronous loading, meaning a module is fully loaded before execution continues
// math.js file  
const add = function(x, y) {
return x + y;
};

module.exports = {
add: add,
};
// app.js file  
const math = require("./math");
console.log(math.add(1, 2)); // Output: 3

ES6 Modules (ESM)

  • ES6 Modules are the modern standard supported by all major browsers
  • ES6 Modules offers features like dynamic imports and tree-shaking
  • It uses import/export syntax for importing and exporting modules
  • ES6 Modules support both synchronous and asynchronous module loading
  • ES6 Modules supported by both browsers and server-side runtimes.
  • The recommended approach for using ES6 modules in Node.js is to use the .mjs file extension. This extension signals to Node.js that the file contains ES6 modules.

Example

// math.js file
export const add = (x, y) => {
return x + y;
};

// app.js file
import { add } from "./math.js";

const result = add(4, 5);
console.log(result); // Output: 9

Summary

  • Use CommonJS for server-side Node.js projects with synchronous loading of modules
  • Use AMD for browser-based applications requiring asynchronous loading
  • Use ES6 Modules for modern JavaScript projects with good browser support and bundling tools like Webpack or Rollup