Ale*_*exZ 4 javascript module requirejs
我在requireJS中遇到了一些上下文问题.我想要的是在配置阶段(在我加载任何模块之前)创建一个上下文"mycontext",然后保持整个上下文.这很复杂,因为我很遗憾需要(< - ha!)为我的模块使用CommonJS语法.所以,如果这是我的基本文件,如下所示:
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();
});
})();
Run Code Online (Sandbox Code Playgroud)
然后,我加载topModule:
http://www.example.com/src/topModule.js
define(['require', 'jquery', 'nestedModule'], function (require) {
var $ = require('jquery');
var other = require('nestedModule');
});
Run Code Online (Sandbox Code Playgroud)
jQuery是否仍然只在mycontext中加载?如果我更进一步怎么办:
http://www.example.com/src/nestedModule.js
define(function (require) {
var $ = require('jquery');
var oneMore = require('someOtherModule');
});
Run Code Online (Sandbox Code Playgroud)
我们已经在这个上下文中访问了jquery,但是"someOtherModule"也会在这个上下文中加载,还是在全局"_"上下文中加载?在进行require调用之前,有没有办法检查模块是否已经加载?
谢谢!
好的,所以我自己想出来了.要求,在本地或全局,有一个非常有用的属性称为".s",其中列出了所有需求上下文.在我的requrie完成加载后,我在控制台上运行了"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);
Run Code Online (Sandbox Code Playgroud)
输出如下:
//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
],
[...]
}
Run Code Online (Sandbox Code Playgroud)
总而言之,我的预感是正确的:当在特定上下文中加载顶级requireJS模块时,即使不再指定上下文,也会在上下文中加载从该顶级模块中加载的所有模块.