Question

I'm developing an applicattion with RequireJS and i have a module used as dependece. All dependences's libraries are in "lib/vendor", so, assumming it calls "MyModule", it is in "lib/vendor/MyModule/my.js.." In my main.js i have:

    3 requirejs.config({
    4     paths: {
    5         my: './vendor/MyModule/my',
    ....

And it works, but the problem is that "my.js" includes some files too

define(["./lib/a", "./lib/b"], function (a,b) {
    ....
});

These files "a.js" and "b.js" are inside of module's folder, so the structure should be something like this:

index.html
lib
   main.js
   vendor
        MyModule
            my.js
            lib
                a.js
                b.js

The problem is when my.js invoked to "a.js" or "b.js" RequireJS tries to find them to "host.com/lib/lib/a.js" instead "host.com/lib/vendor/MyModule/lib/a.js" According "http://requirejs.org/docs/api.html#defdep" the thing i'm doing it should work, but it is not happening

Était-ce utile?

La solution

The problem is that relative dependencies are loaded relative to the name of your module rather than its path. You refer to this example:

//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {

This will work only if the my/shirt.js file is loaded as the my/shirt module. In other words, there is an assumption in this example that there is no paths setting that will change the modules' paths.

Here is what happens with your code:

  1. RequireJS loads main. You don't set a baseUrl so the baseUrl is set to /lib.

  2. You require my. RequireJS resolves it to /lib/vendor/MyModule/my.js and loads it.

  3. The my module requires ./lib/a and ./lib/b. When RequireJS resolves the relative paths, it uses the current module's name (my) as its starting point. The initial period in the two requirements means "get the directory part of the current module name and add the rest of the path to it." The directory part of my is the empty string, so the two paths become lib/a and lib/b and then are combined with the baseUrl to form /lib/lib/a and /lib/lib/b.

    Note that the paths setting for my is not used at all in this computation.

One way to get around your issue would be to use map instead of paths. Whereas paths associates paths to module names, map associate module names to module names so:

map: {
    '*': {
        my: 'vendor/MyModule/my'
    }
}

This tells RequireJS that in all modules (*) if the module with name my is required, the module with name vendor/MyModule/my is loaded.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top