RequireJS:具有不同名称的相同模块

时间:2014-03-13 08:52:37

标签: build requirejs r.js

是否可以在RequireJS中以不同的名称使用相同的模块? (最感兴趣的是优化版)

示例

我依赖于依赖于lodash的兼容AMD的库。我的代码中已经有underscore,我希望该库使用它而不是lodash

当然我不想修改库的来源。所以我修改了require.js配置:

paths: {
  'underscore': 'vendor/underscore', // that's for my code
  ...
  'lodash': 'vendor/underscore', // that's for the new library
}

现在,当试图建立时,r.js抛弃了不幸的人:

The following modules share the same URL. 
This could be a misconfiguration if that URL only has one anonymous module in it:
   /.../underscore.js: lodash, underscore

有没有办法以2个或更多不同的名称注册同一个模块?

1 个答案:

答案 0 :(得分:3)

通常,为需要Lodash的代码加载Underscore是不安全的。唯一的例外是,如果您100%确定相关代码在其Underscore兼容模式下使用Lodash。

如果您确定在特定情况下它是安全的,那么我会使用map处理您的具体问题:

map: {
    "*": { 'lodash': 'underscore'}
}

这告诉RequireJS,无论何处lodash都需要,请改回underscore

如果需要lodashunderscore,上述方法将返回单个模块实例。如果有人想要在两个不同的名称下加载两次相同的模块代码并希望将模块状态分开,则无法使用。例如,一个用于注册名称的模块。如果有人想要在名称foobar下加载此模块,并保持两个注册表分开,以便在foo中注册但未在bar不在bar中(反之亦然),那么他们需要两个模块实例,因此除了使用map之外还需要做其他事情。

相关问题