检测_是lodash还是下划线

ran*_*ame 10 javascript underscore.js lodash

什么是"权威"方法来检测_变量是否加载了lodash或下划线?

我在有时也可以加载下划线的环境中使用lodash进行项目.

目前,我想出了这个:

/** 
 * lodash defines a variable PLACEHOLDER = '__lodash_placeholder__'
 * so check if that is defined / contains the string "lodash"
 */
if ( typeof( _.PLACEHOLDER ) == 'undefined' || _.PLACEHOLDER.indexOf( 'lodash' ) < 0 ) {
    // _ is underscore, do what I need to access lodash
}
Run Code Online (Sandbox Code Playgroud)

重要更新:以上代码不起作用!

是否有一种"权威"方式来检测是否_是lodash或下划线?

注意:
这是一个特定的请求,用于确定是否在_变量中加载了lodash或下划线:
1.无论是否加载下划线,我都无法控制.(lodash 我的控制范围之内,而且将永远被载入).
2.不能依赖lodash /下划线的加载顺序.
3.加载的下划线版本可能会更改(它是可以更新的CMS框架的一部分).
4. Lodash 4.17.x有300多个功能.我的代码使用 lodash中的许多功能.
5. Lodash包含许多下划线提供的功能.
6.两个库中存在的一些函数具有不同的实现.

yuv*_*lio 5

与@bhantol 已经指出的类似,有一个迁移文档,其中列出了兼容的lodash 和下划线之间的差异。那些不能用吗?例如,

if ( typeof( _.invoke ) !== 'undefined' ){
    // it's lodash
}
Run Code Online (Sandbox Code Playgroud)

但是,是的,放大@felix-kling 和@tadman 等人的评论,如果可能的话,将问题限制在功能(例如:特定方法)级别而不是整个库中可能更可靠。

  • `_.invoke` 在两者上都可用。`_.at` 将是一个更好的选择(自 v1 以来仅在 lodash 上) (5认同)

ran*_*ame 2

问题中发布的代码不起作用,就像PLACEHOLDER在缩小过程中重命名的私有变量一样。

因此,我采用了评论中提到的“特征检测”的概念。请注意,如果下划线的未来版本包含所有这些函数,或者如果 lodash 弃用任何这些函数,则此方法可能会崩溃:

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
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.js"></script>
Run Code Online (Sandbox Code Playgroud)