在RequireJS环境中同时使用Lo-Dash和Underscore

8
在RequireJS环境中,允许一些AMD模块使用Lo-Dash,同时允许其他模块使用Underscore,这种情况下最好的方法是什么?

7
为什么不直接使用 Lo-dash?Lo-dash 应该可以完全替代 Underscore(但反之则不行),您需要将其作为翻译。 - mu is too short
我有一些遗留模块,它们与 Lo-Dash 不兼容,需要与使用 Lo-Dash 的新模块同时运行。重构和测试旧模块目前不可行。 - Donald T
与普遍的看法和声称相反,Lo-Dash并不是Underscore的完美替代品。 - Donald T
2个回答

7

我能够相对简单地自己解决这个问题。具体来说,对于需要 Lo-Dash 的模块,请使用 lodash 路径;对于需要 "underscore" 的模块,请使用 underscore

require.config({
  paths: {
    'underscore': 'path-to-my-underscore-file',
    'lodash': 'path-to-my-lodash-file'
  }
});

以这种方式,两个库可以同时使用而不会相互干扰。
与普遍信仰和说法相反,Lo-Dash并不是Underscore的完美替代品。

我不确定除了Lo-Dash之外还有谁声称Lo-Dash是Underscore完美的替代品,也许只有Lo-Dash自己吧? - Xaxis
1
这个问题的第一个评论收到的点赞数量表明了普遍误解。这可能是因为Underscore和Lo-Dash都使用“_”全局变量所致。 - Donald T

5

你已经提到的路径解决方案是一个选项(我认为这是更好的选项)。我知道另一种方法,但我不一定认为它更好,因为它更具欺骗性。你可以重新定义各个软件包中“lodash”和“underscore”的含义。

requirejs.config({
    paths: {
        'underscore': 'path-to-my-underscore-file',
        'lodash': 'path-to-my-lodash-file'
    },
    map: {
        'some/lodash_compatible_module': {
            'underscore': 'lodash'
        },
        'some/lodash_compatible_folder': {
            'underscore': 'lodash'
        },
        'some/oldmodule_or_folder': {
            'underscore': 'underscore'
        }
    }
});

如果您想创建一个外观,也可以像这样做:
requirejs.config({
    paths: {
        utils: 'lodash',
        'underscore': 'path-to-my-underscore-file',
        'lodash': 'path-to-my-lodash-file'
    },
    map: {
        'some/lodash_compatible_module': {
            'utils': 'lodash'
        },
        'some/lodash_compatible_folder': {
            'utils': 'lodash'
        },
        'some/oldmodule_or_folder': {
            'utils': 'underscore'
        }
    }
});

虽然这种方法也存在一些负面因素,但也有一些很酷的东西。比如能够重新映射第三方依赖项可能认为的包(如果这是一个问题的话)。
要了解更多关于map如何工作的信息,请查看:http://requirejs.org/docs/api.html#config-map

非常有趣的连线! - Donald T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接