1
我正在使用RequireJs在我公司的主要網站上加載AMD模塊。我們還使用requireJS來加載託管在不同域上的模塊。 requireJS使用「context」字段來支持它;即。用單獨的baseUrl創建一個單獨的沙盒環境。多上下文requirejs並繼承上下文之間的依賴關係
當前的問題是我們希望兩個單獨的上下文共享一個共同的對象;例如。 jquery(避免加載兩次)或者一個pubsub實現來觸發小部件之間的事件。
我已經想通的方式在上下文之間注入模塊,採用了具有全球requireJS一起定義功能
main.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($);
});
});
的問題是,如果im定義的jQuery(或返回功能的任何其它模塊),TJE「requreJS」往來港澳(不使用全局變量),它總是拋出一個錯誤
// define jquery into sandboxed environemnt
requireJs('jquery', function($) {
define('jquery', $);
});
這是一個錯誤或特徵?