In the world of JavaScript, modularity is key to writing clean, maintainable, and scalable code. Two popular module formats that have emerged to facilitate this are AMD (Asynchronous Module Definition) and UMD (Universal Module Definition). These formats help developers manage dependencies and organize code in a modular fashion, making it easier to maintain large codebases.
Today, both module systems play important roles in JavaScript development, especially in environments where compatibility across different module systems is crucial. AMD is widely used for browser-based applications to load modules asynchronously, improving performance, while UMD provides a versatile solution that works across both client-side and server-side environments, ensuring broad compatibility.
AMD
The idea with AMD was to bring require known from NodeJS to the browser but loading the modules asynchronously. The following example only works if you have requirejs on your website.
// Define define(['dependency'], function (dependency) { return function() { /*...*/ }; }); // Require require(['module'], function(module) { // Use module });
It’s less common to use AMD with TypeScript directly. Most often, TypeScript is used with CommonJS or ES6 Modules.
UMD
Basically, a UMD module is a JavaScript file that tries to guess at runtime which module system it’s being used in, and then it acts as that kind of module. So you can load the file in a plain <script>
, or you can load it from an AMD module loader, or you can load it as a Node.js module, and it will always do something sensible.
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['dependency'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS module.exports = factory(require('dependency')); } else { // Browser global root.returnExports = factory(root.dependency); } }(typeof self !== 'undefined' ? self : this, function (dependency) { // Module definition }));