javascript - require.js jQuery noConflict shim - 为什么从不调用 init 方法

标签 javascript jquery requirejs

我想摆脱全局 jQuery 对象(window.$,也许还有 window.jQuery)。

主要数据:

require.config({
    paths: {
        "jquery": "jquery-2.0.0"
    },
    shim: {
        "bootstrap": {
            deps: ["jquery"]
        },
        "jquery": {
            deps: [],
            init: function() {
                return this.jQuery.noConflict(true);
            },
            exports: "jQuery"
        }
    }
});

require(["jquery", "bootstrap"], function($) {
    // ...
});

这段代码有什么问题?永远不会调用“init”。

最佳答案

最近更新的Use with jQuery RequireJS 网站上的页面解释了更多关于为什么会发生这种情况以及您可以采取什么措施来解决它。这是相关部分:

jQuery registers itself as the global variables "$" and "jQuery", even when it detects AMD/RequireJS. The AMD approach advises against the use of global functions, but the decision to turn off these jQuery globals hinges on whether you have non-AMD code that depends on them. jQuery has a noConflict function that supports releasing control of the global variables and this can be automated in your require.config, as we will see later.

如果你想抑制这些全局函数,你需要使用 map 配置到 noConflict 包装器模块,而不是 shim 配置。正如@tomaskirda 指出的那样,jQuery 不会为支持 AMD 的库触发 shim.init。相关代码来自Use with jQuery页:

require.config({
    // Add this map config in addition to any baseUrl or
    // paths config you may already have in the project.
    map: {
      // '*' means all modules will get 'jquery-private'
      // for their 'jquery' dependency.
      '*': { 'jquery': 'jquery-private' },

      // 'jquery-private' wants the real jQuery module
      // though. If this line was not here, there would
      // be an unresolvable cyclic dependency.
      'jquery-private': { 'jquery': 'jquery' }
    }
});

// and the 'jquery-private' module, in the
// jquery-private.js file:
define(['jquery'], function (jq) {
    return jq.noConflict( true );
});

关于javascript - require.js jQuery noConflict shim - 为什么从不调用 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736663/

相关文章:

jquery - 如何让我的 jQuery UI "close"按钮显示在 DIV 的右上角而不妨碍文本的流动?

jquery - animation.css 和基础

RequireJS 模块相互引用

javascript - 我如何访问requirejs中定义之外的变量

JavaScript:让代码每分钟运行一次

javascript - 上传后双倍大小的文件

JavaScript - 如何检查命令的执行是否完成?

javascript - "document.createElement"性能

javascript - RequireJS'ing 一个没有全局 $ 变量的 jQuery 插件

javascript - 将 PHP 数组发送到回显字符串中调用的 JS 函数