【问题标题】:RequireJS jQuery plugin shim not working?RequireJS jQuery 插件垫片不工作?
【发布时间】:2014-09-16 14:25:47
【问题描述】:

当在 noconflict/noglobal 状态下使用 jQuery 以强制所有模块指示它们是否需要 jQuery 时,我正在尝试让 jQuery 插件与 RequireJS 一起正常工作。但是,对于非 AMD 友好的插件,shim 配置似乎不起作用。即,如果一个 jQuery 插件是用如下包装器定义的:

(function($) {
  $.extend($.myPlugin, { myPlugin: { version:'0.0.1'} });
})(jQuery);

那么下面的 RequireJS 配置不起作用:

requirejs.config({
  paths: {
    jquery: ['//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min', 'jquery-min'],
  },
  map: {
    '*': { 'jquery': 'jquery-noglobal' }, // Force all modules to use the non-global jQuery...
    'jquery-noglobal': { 'jquery': 'jquery' } // ...except the wrapper module itself, which  needs the real one.
  },
  shim: {
    'sadPlugin': {
      deps: ['jquery']
    }
  }
});

jquery-noglobal.js:

define(['jquery'], function(jq) {
  return jq.noConflict( true );
});

插件代码运行时触发的错误是:“无法在undefined 上调用extend”,这意味着jQuery 从未设置在外部级别,因此$ 在自我内部未定义执行功能。我在插件自执行函数之外设置断点,并在内部进行验证。

我猜部分问题是大写;该模块被编写为期望jQuery(驼峰式),而AMD模块名称为jquery(小写)。 shim 配置中是否有任何方法可以指定注入需求的变量名称应该是什么?

我还尝试将sadPlugin: {'jquery':'jquery'} 条目添加到map 哈希,希望使shim 为该模块提供全局jQuery 而不是非全局的,但仍然没有定义jQuery/$到函数被调用时。

编辑:找到了一个可以解决部分问题的问题:根据here 的评论,shimdeps 需要是完整文件要加载的脚本的路径,并且不能是paths 配置的别名。

所以,既然我的 jQuery 的 CDN-fallback 文件是 jquery-min.js,如果我这样做:

shim: {
  'sadPlugin': {
    deps: ['jquery-min']
  }
}

插件有效!然而,由于现在使用的是“真正的”jQuery,它污染了全局命名空间,然后 $ 变量在没有 require() 的情况下可用,因此破坏了 noglobal 包装器的全部目的......

【问题讨论】:

    标签: javascript jquery requirejs


    【解决方案1】:

    随便用

    return jQuery.noConflict( true );
    

    而不是

    return jq.noConflict( true );
    

    所以,作为requirejs中的局部变量,你的插件可以使用变量jQuery作为参数$

    (function($) {$.extend($.myPlugin, { myPlugin: { version:'0.0.1'} });})(jQuery);
    

    适合我的配置是:

    -- main.js

    -- jquery-private.js

    在 main.js 文件中:

    require.config({
      paths: {
      },
      map: {
        '*': { 'jquery': 'jquery-private' },
        'jquery-private': { 'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' }
    
      },
      shim: {
        myplugins: ['jquery']
      }
    });
    

    在 jquery-private.js 文件中:

    define(['jquery'], function () {
      jQuery = $.noConflict(true);
      return jQuery;
    });
    

    【讨论】:

      猜你喜欢
      • 2013-11-28
      • 2015-02-04
      • 2015-03-14
      • 1970-01-01
      • 2015-04-21
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多