Skip to content

Instantly share code, notes, and snippets.

@tejacques
Last active July 25, 2023 12:54
Show Gist options
  • Save tejacques/202a8f2d198ddd54a409 to your computer and use it in GitHub Desktop.
Save tejacques/202a8f2d198ddd54a409 to your computer and use it in GitHub Desktop.
; (function (global, define) { define('module-name', function (require, exports, module) {
// CommonJS style code here
/*!
* UMD/AMD/Global context Module Loader wrapper
* based off https://gist.github.com/tejacques/202a8f2d198ddd54a409
*
* This wrapper will try to use a module loader with the
* following priority:
*
* 1.) AMD
* 2.) CommonJS
* 3.) Context Variable (this)
* - window in the browser
* - module.exports in node and browserify
*/
});})(
typeof window == 'object' ? window : global,
typeof define == 'function' && define.amd ? define : (function (context) {
'use strict';
return typeof module == 'object' ? function (name, factory) {
factory(require, exports, module);
}
: function (name, factory) {
var module = {
exports: {}
};
var require = function (n) {
if (n === 'jquery') {
n = 'jQuery';
}
return context[n];
};
factory(require, module.exports, module);
context[name] = module.exports;
};
})(this));
@tejacques
Copy link
Author

The main advantage of this style is that you can automate it very easily from regular CommonJS, and it also takes care of the problem of referring to jQuery as jquery for standard require but as window.jQuery in the browser.

This has been tested to work with

  • requirejs
  • r.js
  • node
  • browserify
  • browser script tags

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment