public
Last active

Kit's Universal Module Pattern

  • Download Gist
universal-module.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
(function (root, Library) {
// The square bracket notation is used to avoid property munging by the Closure Compiler.
if (typeof define == "function" && typeof define["amd"] == "object" && define["amd"]) {
// Export for asynchronous module loaders (e.g., RequireJS, `curl.js`).
define(["exports"], Library);
} else {
// Export for CommonJS environments, web browsers, and JavaScript engines.
Library = Library(typeof exports == "object" && exports || (root["Library"] = {
"noConflict": (function (original) {
function noConflict() {
root["Library"] = original;
// `noConflict` can't be invoked more than once.
delete Library.noConflict;
return Library;
}
return noConflict;
})(root["Library"])
}));
}
})(this, function (exports) {
// ...
return exports;
});

There should be no need to wrap the noConflict property's IIFE in parentheses because function declarations are not allowed in that context. Also, you can just return a noConflict named function expression directly instead of using a function declaration.

      "noConflict": function (original) {
        return function noConflict() {
          root["Library"] = original;
          // `noConflict` can't be invoked more than once.
          delete Library.noConflict;
          return Library;
        };
      }(root["Library"])

@michaelficarra Indeed, the extra parentheses are a stylistic preference. Returning a named function expression will throw a syntax error in Safari 2, though. It's an outdated browser, but I strive to support it where possible.

@kitcambridge, I am likely going to advocate something like this gist for the AMD folks. If you see any weaknesses, please feel free to let me know.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.