我找到了问题的答案和解决方案(它们显然不一样)。我想我会在这里发布它以防将来对其他人有所帮助。
基本上我想要的是在自己的上下文中加载我的框架。我在require 的网站上的configuration section 和example of how to use it 下找到了上下文选项。最初我尝试这样做:
var req = require.config({
baseUrl: 'framework',
context: 'framework',
paths: {
jQuery: 'lib/jquery/jquery-1.7.min.js',
Underscore: 'lib/underscore/underscore.min.js',
Backbone: 'lib/backbone/backbone.min.js',
etc...
}
});
req(['main'], function() {});
这有两个问题。首先,我的“req”变量是在框架之外定义的,但我希望框架定义它自己的路径。其次,每当框架外的文件需要框架内的文件时,例如,这又需要'jQuery',那么框架实例的上下文中就不需要jQuery(或其他任何东西)的要求,所以它找不到文件。
我最终做的是将我的框架的 main.js 定义为如下所示:
var paths = {
jQuery: 'lib/jquery/jquery-1.7.min.js',
Underscore: 'lib/underscore/underscore.min.js',
Backbone: 'lib/backbone/backbone.min.js',
etc...
};
define(function() {
var exports = {};
exports.initialize = function(baseUrl, overridePaths, callback) {
if(!overridePaths) {
overridePaths = {};
}
if(baseUrl && baseUrl[baseUrl.length - 1] != '/') {
baseUrl = baseUrl + '/';
}
var fullpaths = {};
for(var path in paths) {
// Don't add baseUrl to anything that looks like a full URL like 'http://...' or anything that begins with a forward slash
if(paths[path].match(/^(?:.*:\/\/|\/)/)) {
fullpaths[path] = paths[path];
}
else {
fullpaths[path] = baseUrl + paths[path];
}
}
var config = {paths: fullpaths};
for(var pathName in overridePaths) {
config.paths[pathName] = overridePaths[pathName];
}
require.config(config);
// Do anything else you need to do such as defining more functions for exports
if(callback) {
callback();
}
}
return exports;
});
然后在我的项目的 main.js 文件中,我只是这样做:
require(['framework/main'], function(framework) {
// NOTE: This setTimeout() call is used because, for whatever reason, if you make
// a 'require' call in here or in the framework without it, it will just hang
// and never actually go fetch the files in the browser. There's probably a
// better way to handle this, but I don't know what it is.
setTimeout(function() {
framework.initialize('framework', null, function() {
// Do stuff here
}
}, 0);
});
这会将传入框架的 initialize() 方法的任何内容用于“baseURL”,并将其添加到框架定义的不以正斜杠或“anything://”开头的任何路径,除非它们被覆盖路径。这允许使用框架的包覆盖诸如“jQuery”之类的东西。