最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent conflict between lodash and underscore on front-end - Stack Overflow

programmeradmin2浏览0评论

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
 |  Show 1 more ment

1 Answer 1

Reset to default 15

On 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>
发布评论

评论列表(0)

  1. 暂无评论