Prevent conflict between lodash and underscore on

2019-02-19 13:04发布

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?

1条回答
SAY GOODBYE
2楼-- · 2019-02-19 13:58

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 commented 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>
查看更多
登录 后发表回答