Skip to content

Instantly share code, notes, and snippets.

@ryanburnette
Last active June 1, 2021 22:02
Show Gist options
  • Save ryanburnette/cbb228681c4a288ec07c07fded0169f1 to your computer and use it in GitHub Desktop.
Save ryanburnette/cbb228681c4a288ec07c07fded0169f1 to your computer and use it in GitHub Desktop.
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
Copy link

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