Context and nested modules in requireJS

2019-05-06 06:35发布

问题:

I'm having a bit of trouble with contexts in requireJS. What I'd like to is create a context, "mycontext", at the config stage (before I load any modules), and then have that context kept throughout. This is complicated because I am unfortunately required (<- ha!) to use the CommonJS syntax for my modules. So, if this is my base file looks like this:

base.js

contextReq = require.config({
    context: 'mycontext',
    baseUrl: 'http://www.example.com/src/',
    paths:{
        jquery: 'http://ajax.cdnjs.com/ajax/libs/jquery/2.0.3/jquery.min',
    },
});

(function(){
    contextReq(['require', 'topModule'], function(require, topModule){
        topModule.initialize();
    });
})();

Then, I load topModule:

http://www.example.com/src/topModule.js

define(['require', 'jquery', 'nestedModule'], function (require) {
    var $ = require('jquery');
    var other = require('nestedModule');
});

Will jQuery still be loaded only in mycontext? What if I go a level further:

http://www.example.com/src/nestedModule.js

define(function (require) {
    var $ = require('jquery');
    var oneMore = require('someOtherModule');
});

We already have access to jquery in this context, but will "someOtherModule" also be loaded in this context, or in the global "_" context? Is there any way to check if a module is already loaded before I make the require call?

Thanks!

回答1:

Ok, so I figured this out myself. Require, locally or globally, has a very useful property called ".s" which lists, among other things, all of requires contexts. I ran "require.s.contexts" on to the console after my requrie has finished loading:

base.js

contextReq = require.config({
    context: 'mycontext',
    baseUrl: 'http://www.example.com/src/',
    paths:{
        jquery: 'http://ajax.cdnjs.com/ajax/libs/jquery/2.0.3/jquery.min',
    },
});

(function(){
    contextReq(['require', 'topModule'], function(require, topModule){
        topModule.initialize();
    });
})();

//Timeout, then see where we stand
setTimeout( function () {
    console.log(require.s.contexts._);
    console.log(require.s.contexts.mycontext);
}, 500);

The output was as follows:

//Console.log for context '_' (the default require context)
{
     [...]
     defined: [], //empty array, nothing has been loaded in the default context
     [...]
}

//Console.log for context 'mycontext' (the default require context)
{
     [...]
     defined: [ //Filled out array; everything is loaded in context!
          topModule: Object
          nestedModule: Object
          jquery: function (e,n){return new x.fn.init(e,n,t)} //jQuery function
     ],
     [...]
}

So, in summary, my hunch was correct: when a top level requireJS module is loaded in a particular context, all modules loaded from within that top level module are loaded in context, even if the context is no longer specified.