Adam Rackis
Adam Rackis

Reputation: 83376

Dynamically resolve paths with RequireJS

Is there a way to dynamically resolve paths with RequireJS? For example, is it possible to configure it so that, if I do

require(['mymodule'], function(mod){ });

some sort of function of mine will be called, with "mymodule" being passed as a parameter, and with the value I return therefrom being used by Require as the path to use for mymodule?


I do understand that Require has some wonderful convention over configuration with respect to path resolution, and I also understand that paths can be manually configured. But right now I'm trying to add in RequireJS to an old project that was written without Require in mind, so I'm trying to see what all of my options are.

Upvotes: 2

Views: 3042

Answers (1)

Steve P
Steve P

Reputation: 19397

You might be best served by implementing a loader plugin.

Not sure if it's a problem for you, but this would mean your require syntax would turn into something like this:

require(['myplugin!mymodule'], function(mod){ });

The specific method you would use is normalize:

normalize is called to normalize the name used to identify a resource. Some resources could use relative paths, and need to be normalized to the full path. normalize is called with the following arguments:

EDIT: I see there's a replace plugin listed on the plugins wiki which sounds similar to what you are trying to do. It uses only the load method, so apparently what I said above about the normalize method is not a blanket rule.

If the path is truly dynamic, this won't help, but if you just need to modify how the legacy script is returned back to your modules (e.g. taking two different globals and putting them under a different top-level global), you might also think about using the init hook in the shim config option

EDIT 2: some related hacks are posted in this question: Configuring RequireJS to load from multiple CDNs

Upvotes: 2

Related Questions