javascript - requireJS 中的上下文和嵌套模块

标签 javascript module requirejs

我在使用 requireJS 中的上下文时遇到了一些麻烦。我想要的是在配置阶段(在加载任何模块之前)创建一个上下文“mycontext”,然后始终保留该上下文。这很复杂,因为不幸的是我需要(<- 哈!)为我的模块使用 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();
    });
})();

然后,我加载 topModule:

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

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

jQuery 是否仍然只在 mycontext 中加载?如果我更进一步会怎样:

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

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

我们已经可以在此上下文中访问 jquery,但是“someOtherModule”是否也会在此上下文中或全局“_”上下文中加载?在调用 require 之前,有什么方法可以检查模块是否已经加载?

谢谢!

最佳答案

好的,所以我自己想通了。 Require,本地或全局,有一个非常有用的属性,称为“.s”,它列出了所有需要的上下文。在我的 require 完成加载后,我在控制台上运行了“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 模块时,从该顶级模块中加载的所有模块都会在上下文中加载,即使不再指定上下文也是如此。

关于javascript - requireJS 中的上下文和嵌套模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279196/

相关文章:

javascript - 定义模块并立即使用 RequireJS

node.js - Uncaught ReferenceError : require is not defined in Electron

javascript - ngRoute 和 Underscore.js 的 RequireJS shim 配置

javascript - 将重复的 mysql 结果分组到同一结果下

node.js - 如何在 Node 8 的 Node.js REPL 中导入 ES 模块?

Javascript : Stop setInterval using clearInterval

javascript - ES6 模块的问题

javascript - EventEmitter2 的 require.js shim 配置

javascript - 在 CSS 类中为图像赋值

javascript - 如何在回调方法中保留 'this'?