Domanda

Is it possible to use the same module under different names in RequireJS? (Mostly interested in optimized version)

Example

I depend on an AMD-compatible library that depends on lodash. I already have underscore in my code and I want that library to use it instead of lodash.

Of course I do not want modify library's source. So I modify the require.js configuration:

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

And now when trying to build, r.js throws the unfortunate:

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

Is there a way to register the same module under 2 or more different names?

È stato utile?

Soluzione

In general it is not safe to load Underscore for code that requires Lodash. The one exception is if you are 100% sure that the code in question used Lodash in its Underscore-compatible mode.

If you have determined that it is safe in your specific case, then I would handle your specific problem by using a map:

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

This tells RequireJS that everywhere lodash is required, give back underscore instead.

The method above returns a single module instance if lodash or underscore are required. It would not work in a case someone would want to load the same module code twice under two different names and would want to keep module state separate. For instance, a module which is meant to register names. If someone would want to load this module under names foo and bar and keep the two registries separate so that what is registered in foo is but not registered in bar is not in bar (and vice-versa) then they would need two module instances and thus would have to do something else than use map.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top