Mat*_*zzi 27 javascript amd requirejs
我正在为我开发的javascript库添加AMD支持.
这个库可能使用jquery但是如果没有加载jquery它仍然可以工作.
在定义模块依赖项时,有一种方法可以将依赖项设置为"可选",这样如果缺少该库,模块仍然可以工作吗?
Lor*_*igs 26
我最近遇到了完全相同的问题,这就是我修复它的方法.我定义了一个RequireJS插件optional,它通过显式地将它们定义为空对象来忽略无法加载的模块(但我想你也可以将它定义为null或其他任何你想要的).
这是代码(使用RequireJS 2.1.15测试):
define("optional", [], {
load : function (moduleName, parentRequire, onload, config){
var onLoadSuccess = function(moduleInstance){
// Module successfully loaded, call the onload callback so that
// requirejs can work its internal magic.
onload(moduleInstance);
}
var onLoadFailure = function(err){
// optional module failed to load.
var failedId = err.requireModules && err.requireModules[0];
console.warn("Could not load optional module: " + failedId);
// Undefine the module to cleanup internal stuff in requireJS
requirejs.undef(failedId);
// Now define the module instance as a simple empty object
// (NOTE: you can return any other value you want here)
define(failedId, [], function(){return {};});
// Now require the module make sure that requireJS thinks
// that is it loaded. Since we've just defined it, requirejs
// will not attempt to download any more script files and
// will just call the onLoadSuccess handler immediately
parentRequire([failedId], onLoadSuccess);
}
parentRequire([moduleName], onLoadSuccess, onLoadFailure);
}
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以选择简单地使用模块
require(['optional!jquery'], function(jquery){...});
Run Code Online (Sandbox Code Playgroud)
知道如果无法加载jquery模块,传递给回调函数的参数将是一个空对象.
asg*_*oth 12
您无法将其设置为可选,但您可以捕获错误并使用undef以下命令卸载模块:
require(['jquery'], function ($) {
//Do something with $ here
}, function (err) {
//The errback, error callback
//The error has a list of modules that failed
var failedId = err.requireModules && err.requireModules[0];
if (failedId === 'jquery') {
//undef is function only on the global requirejs object.
//Use it to clear internal knowledge of jQuery. Any modules
//that were dependent on jQuery and in the middle of loading
//will not be loaded yet, they will wait until a valid jQuery
//does load.
requirejs.undef(failedId);
...
}
});
Run Code Online (Sandbox Code Playgroud)
完整的例子在这里.