I just took a shot at wrapping one of our modules that is meant to be included via a <script>
tag in some boilerplate to allow optional AMD loading with requirejs.
It was quite painful and the best I could come up with is:
(function(){
var exports, jQuery;
if (typeof window.define === 'function' && typeof window.requirejs === 'function') {
exports = {};
define(['jquery'], function (jq) {
jQuery = jq;
return thisModule();
});
} else {
exports = window;
jQuery = window.jQuery;
thisModule();
}
function thisModule() {
}
})();
Notice that this is
- A LOT of boilerplate
- Requires you to declare dependencies in variables (only jQuery in this case thankfully) AND amd
- Needs yet more code if I want to have CommonJs support.
I am primarily concerned about the second point as that one is going to be a doozy when I get beyond wrapping our core files. I'm sure there's some neat(er) wrapper implementations out there but I can't find any.
Anyone have any tips?
typeof window.requirejs == 'function'
. You probably don't care about the AMD implementation. Instead testwindow.define.amd
. But that's just a tweak. – Otis