RequireJS - jQuery 区分大小写吗?

2023-12-12

我正在尝试开始使用 RequireJS,但遇到了一个恼人的问题。 。 。

require.config({
    baseUrl: 'app_content/scripts',
    paths: {
        // the left side is the module ID,
        // the right side is the path to
        // the jQuery file, relative to baseUrl.
        // Also, the path should NOT include
        // the '.js' file extension. This example
        // is using jQuery 1.9.0 located at
        // js/lib/jquery-1.9.0.js, relative to
        // the HTML page.
        'jQuery': 'lib/jQuery/jQuery-2.0.3'
    }
});

这个,使用大写Q,不起作用,但如果我将其更改为jquery,确实如此。另外,这在我需要的领域也是如此......

<script type="text/javascript">
    require(["jQuery"], function ($) {
        console.log($);
    });
</script>

这返回undefined,但如果我把一切都改成直线jquery, 有用。

这是预期的行为吗?我能对此做些什么吗?


是的,jQuery 将自己定义为“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.
if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function () { return jQuery; } );
}

所以你必须将其称为"jquery"RequireJS 调用中随处可见。这里的问题是definejQuery 使用的是"named define"这是我们在创建模块时通常不使用的东西。当我们运行 RequireJS 优化器时,它会为我们添加这些名称。

无论如何,当一个“被命名的define" 用于将模块名称设置为给定的名称define而不是通过文件名(当我们不使用命名时的情况)define).

可以重命名"jquery" to "jQuery", 像这样:

require.config({
  baseUrl: "./js",
  paths: {
      "jquery": "jquery-1.10.2"
  }
});

define("jQuery", ["jquery"], function ($) {
   return $;
});

require(["jQuery"], function ($) {
   console.log($);
   console.log($("body")[0]);
});

我正在使用的版本define将名称作为第一个参数。完整示例here.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RequireJS - jQuery 区分大小写吗? 的相关文章

随机推荐