Last active
March 21, 2024 21:38
-
-
Save DarrenSem/79b48e097a54a4a6e00c90354e951af9 to your computer and use it in GitHub Desktop.
Universal Module Definition (UMD) template for JavaScript modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UMD-javascript-module-template.js | |
// Universal Module Definition (UMD) template for JavaScript modules | |
(function(root, factory) { | |
// var req1 = foo, req2 = bar; // or even exports | |
if(typeof exports === "object" && typeof module !== "undefined") { | |
module.exports = factory(req1, req2); | |
} else if(typeof define === "function" && define.amd) { | |
define([req1, req2], factory) | |
} else { | |
root["MOD_NAME"] = factory(req1, req2); | |
}; | |
})( | |
// self so it works in a Worker | |
typeof self !== 'undefined' ? self : this, | |
function(req1, req2) { | |
// var internal_variables; | |
var my_module = {}; | |
// ^ or function or [] or "" or # or ... | |
// var bar = function or object or ... | |
// my_module.public_foo = bar; | |
// for ESM (ES6 modules) import x from "y" | |
my_module.default = my_module; | |
return my_module; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UMD-updated.js -- the most commonly used pattern, including using exports.xyz | |
( (global, factory, name) => { | |
typeof exports == "object" && typeof module != "undefined" | |
? factory(exports) | |
: typeof define == "function" && define.amd | |
? define(["exports"], factory) | |
: ( | |
global = global || self, | |
// global[name] = factory(global[name] = {}) // if function | |
factory(global[name] = {}) // if object | |
); | |
} )( this, exports => { | |
// var foo = (x, y) => x + y; // if function | |
var foo = exports; // if object | |
foo.bar= x => x * x; | |
foo.baz = (x, y) => x ** y; | |
foo.buz = "fiz"; | |
exports.xyzzy = "42"; | |
// return exports.foobar = foo; // if function | |
}, "foobar" ); | |
// NOTE: could minify even smaller (but less clear) by presuming typeof can only be: bigint, boolean, function, number, object, string, symbol, undefined | |
// ^ typeof exports < "s" && typeof module < "u" INSTEAD OF typeof exports == "object" && typeof module != "undefined" , AND typeof define < "n" INSTEAD OF typeof define == "function" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment