There seems to be no bulletproof way to prevent conflict between underscore and lodash on the front-end.
We could do this:
<script src="/scripts/vendor/underscore/underscore.js"></script>
<script>
window._us = window._;
delete window._;
</script>
<script src="/scripts/vendor/lodash/lodash.js"></script>
but that doesn't seem to be good enough. Is there a way to use both libs or do we have to choose?
There seems to be no bulletproof way to prevent conflict between underscore and lodash on the front-end.
We could do this:
<script src="/scripts/vendor/underscore/underscore.js"></script>
<script>
window._us = window._;
delete window._;
</script>
<script src="/scripts/vendor/lodash/lodash.js"></script>
but that doesn't seem to be good enough. Is there a way to use both libs or do we have to choose?
Share Improve this question asked Feb 20, 2016 at 5:51 Alexander MillsAlexander Mills 100k165 gold badges533 silver badges909 bronze badges 6- 2 They have patible APIs, why would you use both? – elclanrs Commented Feb 20, 2016 at 5:52
- we are using some functions from underscore that don't exist on lodash eg _.where – Alexander Mills Commented Feb 20, 2016 at 5:54
- Don't underscore and lodash both have a noConflict() method? (Call the method, don't try to do it manually.) – nnnnnn Commented Feb 20, 2016 at 5:55
-
1
If you need
_.where
or something else that lodash doesn't have, then why don't you just patch it in with_.mixin
? Trying to use both at the same time is, IMO, a mistake. – mu is too short Commented Feb 20, 2016 at 7:01 - 1 you might also review the lodash changelogs to see about replacing functions like underscore's _.where with patible lodash functions (eliminating the need for the underscore dependency) – sfletche Commented Feb 20, 2016 at 14:15
1 Answer
Reset to default 15On the topic of noConflict
, when underscore or lodash are loaded globally they will override the global _
variable. Calling noConflict()
will reverse this, setting _
to its previous value and return the instance of _
. In the example below I mented how the global _
value will change after each action
<!-- the global _ will now be underscore -->
<script src="/scripts/vendor/underscore/underscore.js"></script>
<!-- the global _ will now be lodash -->
<script src="/scripts/vendor/lodash/lodash.js"></script>
<script>
// the global _ will now be underscore
window.lodash = _.noConflict();
// the global _ will now be undefined
window.underscore = _.noConflict();
</script>