Skip to content

Instantly share code, notes, and snippets.

@phawk
Last active February 11, 2024 22:57
Show Gist options
  • Select an option

  • Save phawk/4435601 to your computer and use it in GitHub Desktop.

Select an option

Save phawk/4435601 to your computer and use it in GitHub Desktop.
Defining AMD modules / libraries as AMD, Common JS and browser globals This is a quick way of defining a JS module that will load in any of three environments and allow you to pass in dependencies.
(function (global, $, name, definition) {
// Checks what environment we are in and loads accordingly
if (typeof define === "function" && define.amd) {
// With AMD we require the module with its name rather than passing the variable directly
define(["jquery"], definition); // AMD
}
else if (typeof module !== "undefined" && module.exports) {
// CommonJS will need to require the node module for jQuery
$ = require("jquery");
module.exports = definition($); // CommonJS
}
else {
global[name] = definition($); // Browser global variable
}
})(this, this.$, "ModuleName", function ($) {
// Modules private API
return {
// Modules public API
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment