AMD over UMD
See original GitHub issueThanks for js-cookie!
I’m using js-cookie with Browserify to build a widget. It works on most sites, but it failed on nytimes.com. I figured out was because nytimes.com uses AMD (that is, it has the define function defined in the global namespace) where as Browserify uses UMD.
My code was breaking because js-cookie defined itself via define, which I don’t use at all.
Here’s the current code:
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
I was able to fix it by swapping the order of the checks, so that it checks for UMD ((typeof exports === 'object') before AMD ((typeof define === 'function' && define.amd)).
This just creates the opposite problem though, of preferring UMD over AMD.
In order to accommodate both, what about something like:
var usesAmdOrUMD = false;
if (typeof define === 'function' && define.amd) {
usesAmdOrUMD = true;
define(factory);
}
if (typeof exports === 'object') {
usesAmdOrUMD = true;
module.exports = factory();
}
if (!usesAmdOrUMD) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
This would have the effect of defining it both via AMD and UMD, if they’re both available. I’m not sure if that’s OK or not.
Maybe there’s some other way of allowing either without preferring one over the other? Not sure how that’d be possible though.
I think this is the same issue as #173 and #201 And this is possibly related: #234
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (3 by maintainers)

Top Related StackOverflow Question
Yup, that’s correct!
For my use-case, I don’t need it registered via AMD, just UMD. I don’t see how to have it be one-or-the-other without preferring one of the two, which is why I think it makes sense to load it both ways.
It is a blocker for me, I have to use an edited version of
js-cookie. The trouble is that, in my code, I’m only using UMD. The code I’m working on is a widget which gets loaded onto other sites. To test this, we triednytimes.comwhich uses AMD. So the current release ofjs-cookieloads only via AMD, which means my UMD code cannot access it.Seems like it would be OK to load via both. I can’t think of a case where this change would break someone’s code, but JS loading isn’t my strong suit.
Maybe take a look at how other projects have handled this?