requireJS可选依赖项 [英] requireJS optional dependency

查看:114
本文介绍了requireJS可选依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我开发的javascript库添加AMD支持。

I'm adding AMD support to a javascript library I develop.

这个库可能使用jquery但是如果没有加载jquery它仍然可以工作。

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?

推荐答案

我最近遇到了完全相同的问题,这就是我修复它的方法。我定义了一个名为 optional 的RequireJS插件,它通过将它们显式定义为空对象来忽略无法加载的模块(但我想你也可以将它定义为null或其他任何东西,如果你想要的。)

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).

这是代码(用RequireJS 2.1.15测试):

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){...});

知道如果无法加载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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆