Detecting if _ is lodash or underscore

天大地大妈咪最大 提交于 2019-12-05 01:34:37

Going along similar lines as @bhantol already noted, there is a Migrating doc with a list of differences between lodash and underscore that were not compatibilized with. Can't those be used? For example,

if ( typeof( _.invoke ) !== 'undefined' ){
    // it's lodash
}

But yeah, amplifying comments by @felix-kling and @tadman and others, if possible, it might be more reliable to restrict the question to the feature (e.g.: specific method) level rather than the whole library.

The code posted in the question does not work, as PLACEHOLDER is a private variable that gets renamed during minification.

Therefore, I've adapted the notion of "feature detection" as mentioned in the comments. Note that this method might break down if future versions of underscore roll in all of these functions, or if lodash deprecates any of these functions:

var isLodash = false;
// If _ is defined and the function _.forEach exists then we know underscore OR lodash are in place
if ( 'undefined' != typeof(_) && 'function' == typeof(_.forEach) ) {
  // A small sample of some of the functions that exist in lodash but not underscore
  var funcs = [ 'get', 'set', 'at', 'cloneDeep' ];
  // Simplest if assume exists to start
  isLodash  = true;
  funcs.forEach( function ( func ) {
    // If just one of the functions do not exist, then not lodash
    isLodash = ('function' != typeof(_[ func ])) ? false : isLodash;
  } );
}

if ( isLodash ) {
  // We know that lodash is loaded in the _ variable
  console.log( 'Is lodash: ' + isLodash );
} else {
  // We know that lodash is NOT loaded
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!