RequireJs - 为什么Jquery注入而JSZip不是?

时间:2015-11-19 21:17:02

标签: javascript jquery requirejs

我试图理解requireJs是如何工作的,有人可以向我解释一下,为什么在下面的例子中:

http://plnkr.co/edit/HEDc8F19wICMy0zeGWpH?p=preview

更具体地说:

require(['ble'], function () {
  $('#someDiv').html(Ble.A());//This works fine

  var zip = new JSZip();//This fails with JSZip is not defined
  console.log(zip);
});

定义了Jquery,但JSZip不是?我也尝试了其他组合,但只有一个似乎有用的是我在require数组中手动​​指定jszip,如下所示:

require(['jszip','ble'], function (JSZip) {
  $('#someDiv').html(Ble.A());

  var zip = new JSZip();
  console.log(zip);
});

我知道文档说明:

  

shim配置只设置代码关系。加载模块   属于或使用shim配置,正常的require / define调用是   需要。设置填充程序本身不会触发加载代码。

但是接下来 - 是jquery某种"特殊情况"我通常应该手动注入我的依赖项,即使它们是在shim config部分中指定的吗?

ASWER:

事实证明,jQuery确实是一个特例,通常需要手动注入依赖项...

2 个答案:

答案 0 :(得分:0)

如果你查看source code of jQuery,你会发现以下内容:

// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    });
}

这意味着jQuery将在需要时将自己定义为jquery

答案 1 :(得分:0)

require(['jszip','ble'], function (JSZip) {

在上述声明中,它导入jszip并以JSZip的形式返回对象。

var zip = new JSZip();

在此使用该对象。因此,使用此代码,您不会出错。

因此,对于jszip,仅要求是不够的。