首页 文章

检测_是lodash还是下划线

提问于
浏览
8

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

我正在使用lodash用于有时也可能加载underscore的环境中的项目 .

目前,我想出了这个:

/** 
 * 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
}

Important update: 以上代码不起作用!

是否有"authoritative"方法来检测 _ 是lodash还是下划线?

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

2 回答

  • 3

    与@bhantol已经注意到的类似,有一个Migrating doc,其中包含lodash和下划线之间的差异列表,这些差异未与之兼容 . 不能用那些?例如,

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

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

  • 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
    }
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.3/lodash.js"></script>
    

相关问题