【问题标题】:Multi-context requirejs and inheriting dependencies between contexts多上下文 requirejs 和继承上下文之间的依赖关系
【发布时间】:2013-06-26 20:26:48
【问题描述】:

我正在使用 RequireJs 在我公司的主要网站上加载 AMD 模块。我们还使用 requireJS 来加载托管在不同域上的模块。 requireJS 使用“上下文”字段支持这一点; IE。使用单独的 baseUrl 创建单独的沙盒环境。

当前的问题是当我们希望两个独立的上下文共享一个公共对象时;例如。 jquery(以避免加载它两次)或在小部件之间触发事件的 pubsub 实现。

我想出了一种在上下文之间注入模块的方法,使用定义函数和全局 requireJS

ma​​in.js - 托管在 http://example.com/src/main.js

require(['jquery'], functin($){

    // create sandbox/contexted instance of requireJs 
    var sandbox = requireJS.config({
        context: "myContext",
        baseUrl : 'http://otherdomain.com/src'
    });

    // load module (with internal dependencies) from other domain
    sandbox.require(['modules/bootstrap.js'], function(bootstrap){
        bootstrap.run();
    });

});

bootstrap.js - 例如。托管在http://widgets.com/src/modules/bootstrap.js

define(function(){

    // define jquery into sandboxed environemnt
    requireJs('jquery', function($) {
        define('jquery', function(){
            return window.jQuery;
       });
    });

    // obtain sandboxed instance from parent
    var sandbox = requireJs.config({
        context: "myContext"
    });

    sandbox(['jquery'], function($){
        console.log($);
    });

});

问题是,如果我定义 jquery(或任何其他返回函数的模块),tje "requreJS"-way(不使用全局变量)它总是会抛出错误

    // define jquery into sandboxed environemnt
    requireJs('jquery', function($) {
        define('jquery', $);
    });

这是错误还是功能?

【问题讨论】:

    标签: requirejs amd


    【解决方案1】:

    我实际上自己解决了这个问题。诀窍是将返回的函数包装在一个新的匿名函数中。

    // inject global module into contexted require
    function injectContext(moduleId, module){
        var m = module;
        if(typeof module === 'function') {
            m = function() {
                return module;
            };
        } 
        define(moduleId, m);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2011-04-12
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多