RequireJs-为什么注入Jquery而没有注入JSZip

RequireJs - why is Jquery injected and JSZip is not?

本文关键字:注入 JSZip Jquery 为什么 RequireJs-      更新时间:2023-09-26

我正在努力理解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-config的一部分或使用shim-config,正常的require/define调用是需要。自行设置垫片不会触发代码加载。

但是,jquery是某种"特殊情况"吗?我通常应该手动注入我的依赖项,即使它们是在填充程序配置部分指定的?

ASWER:

因此,jQuery确实是一种特殊情况,通常需要手动注入依赖项。。。

如果你查看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

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

在上面的语句中,它导入jszip并返回一个对象JSZip

var zip = new JSZip();

这里使用的是那个对象。因此,使用此代码,您不会出现错误。

因此,对于jszip来说,仅仅需要是不够的。