eugene
eugene

Reputation: 41765

requirejs define: nested dependency

I'd like to define A, but A should require B and B require C (for the sake of r.js)

Any of the these two are correct?

define([
    'module'
], function(module) {
    require(['C'], function() {
        require(['B'], function() {

            var A;

            return A;
        });
    });
});


require(['C'], function() {
    require(['B'], function() {
        define([
            'module'
        ], function(module) {
            var A;

            return A;
        });
    });
});

Upvotes: 2

Views: 1825

Answers (2)

Louis
Louis

Reputation: 151531

Neither of your choices are correct.

You first choice attempts to use return to return a value from an asynchronous callback. It is generally not possible, and RequireJS is no different. See this question and its answers for why it is that way.

Your second choice puts a define inside a callback passed to require. This may work in some toy cases but in general this just won't work. (By "toy case" I mean proof-of-concepts where all conditions are under tight control. Such cases do not reflect the realities of real applications.)

Linh Pham's suggestion is really your option here:

define(["module", "B", "C"], function(module){
    var A;

    return A;
});

And if B depends on C and is not a AMD library, put a shim for it. In a comment you objected that you'd have to have "hundreds" of shims if you did this. You have a few options to avoid these shims:

  1. Do not load C with RequireJS. Load it with a script element before RequireJS is loaded on your page.

  2. Design your application to be started with just one module and require that your application be started by loading C before anything else:

    require(['C'], function () {
        require(['main']);
    });
    

    main would be the module that starts your application. The disadvantage of this method is that if you are like me, eventually, you are going to forget to require C before you require main.

Upvotes: 5

Linh Pham
Linh Pham

Reputation: 3025

just put deps inside define block, like this:

define(["module", "B", "C"], function(module){
    var A;

    return A;
});

If your module B depend on C then you should config it in your require.config like following

shim: {
    "B": ["C"] // shorthand of "B": {deps: ["C"]}
}

Upvotes: 1

Related Questions