我在requireJS中的上下文有点麻烦。我要在配置阶段(在加载任何模块之前)创建一个上下文“ mycontext”,然后将该上下文始终保留下来。这很复杂,因为很遗憾,我需要(
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();
});
})();
然后,我加载topModule:
http://www.example.com/src/topModule.js
define(['require', 'jquery', 'nestedModule'], function (require) {
var $ = require('jquery');
var other = require('nestedModule');
});
仍将仅在mycontext中加载jQuery吗?如果我更进一步,该怎么办:
http://www.example.com/src/nestedModule.js
define(function (require) {
var $ = require('jquery');
var oneMore = require('someOtherModule');
});
我们已经可以在此上下文中访问jquery,但是是否还会在此上下文或全局“ _”上下文中加载“ someOtherModule”?在进行require调用之前,有什么方法可以检查模块是否已经加载?
谢谢!
好,所以我自己弄清楚了。本地或全局的Require具有一个非常有用的属性,称为“ .s”,该属性除其他外列出了所有需求上下文。我的需求完成加载后,我在控制台上运行了“ require.s.contexts”:
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);
输出如下:
//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
],
[...]
}
因此,总而言之,我的直觉是正确的:当在特定上下文中加载顶层requireJS模块时,即使不再指定上下文,从该顶层模块中加载的所有模块也都在上下文中加载。