Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A universal definition pattern for JavaScript libraries. Supports require(), AMD, and browser.
;(function() {
function myModule() {
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = myModule;
}
else {
if (typeof define === 'function' && define.amd) {
define([], function() {
return myModule;
});
}
else {
window.myModule = myModule;
}
}
})();
@coolaj86

This comment has been minimized.

Copy link

@coolaj86 coolaj86 commented May 28, 2021

Let's say assume AMD is dead. Can I do this?

var myModule;
(function () {

    myModule = { foo: 'bar' };

    if ("undefined" !== typeof module && module.exports) {
        module.exports = myModule;
    }
}());

Or do I have to do this?

;(function () {

    var myModule = { foo: 'bar' };

    if ("undefined" !== typeof module && module.exports) {
        module.exports = myModule;
    } else {
        window.myModule = myModule;
    }
}());
@ryanburnette

This comment has been minimized.

Copy link
Owner Author

@ryanburnette ryanburnette commented May 28, 2021

  1. I definitely think it's safe to drop AMD.
  2. What's the point of declaring the var in the global scope?
@coolaj86

This comment has been minimized.

Copy link

@coolaj86 coolaj86 commented Jun 1, 2021

What's the point of declaring the var in the global scope?

So that it won't interfere with module bundlers that do weird things with window.

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