requireJS 可选依赖 [英] requireJS optional dependency
问题描述
我正在为我开发的 JavaScript 库添加 AMD 支持.
这个库可能会使用 jquery,但如果没有加载 jquery,它仍然可以工作.
在定义模块依赖项时,有一种方法可以将依赖项设置为可选",这样如果缺少该库,模块仍然可以工作?
我最近遇到了完全相同的问题,以下是我修复它的方法.我定义了一个名为 optional
的 RequireJS 插件,它通过将无法加载的模块显式定义为空对象来忽略它们(但我想你也可以将它定义为 null 或其他任何你想要的东西).>
这是代码(使用 RequireJS 2.1.15 测试):
define("可选", [], {负载:功能(模块名称,parentRequire,onload,配置){var onLoadSuccess = 函数(模块实例){//模块加载成功,调用onload回调使//requirejs 可以发挥它的内在魔法.加载(模块实例);}var onLoadFailure = 函数(错误){//可选模块加载失败.var failedId = err.requireModules &&err.requireModules[0];console.warn("无法加载可选模块:" + failedId);//取消定义模块以清理 requireJS 中的内部内容requirejs.undef(failedId);//现在将模块实例定义为一个简单的空对象//(注意:您可以在此处返回您想要的任何其他值)定义(failedId, [], function(){return {};});//现在 require 模块确保 requireJS 认为//加载完毕.由于我们刚刚定义了它,requirejs//不会尝试下载更多的脚本文件和//将立即调用 onLoadSuccess 处理程序parentRequire([failedId], onLoadSuccess);}parentRequire([moduleName], onLoadSuccess, onLoadFailure);}});
然后您可以选择使用简单的模块
require(['optional!jquery'], function(jquery){...});
知道如果无法加载jquery模块,传递给你的回调函数的参数将是一个空对象.
I'm adding AMD support to a javascript library I develop.
This library may use jquery but it will still work if jquery isn't loaded.
When defining the module dependency there's a way to set a dependency as 'optional' so that if that library is missing the module will still work?
I've had exactly the same problem recently, and here's how I fixed it. I defined a RequireJS plugin called optional
which ignores modules that fail to load by explicitly defining them as an empty object (but I suppose you could also define it as null or anything else if you wanted).
Here is the code (tested with 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);
}
});
You can then require a module optionally using simply
require(['optional!jquery'], function(jquery){...});
knowing that if the jquery module could not be loaded, the parameter passed to your callback function will be an empty object.
这篇关于requireJS 可选依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!