如何使用requirejs加载jQuery插件 [英] How to make a jQuery plugin loadable with requirejs

查看:996
本文介绍了如何使用requirejs加载jQuery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用requirejs + jquery,我想知道是否有一种聪明的方法可以使jQuery插件在需要时运行良好。



例如i'我使用jQuery-cookie。如果我理解正确,我可以创建一个名为jquery-cookie.js的文件,并在里面做

  define([jquery], //需要jquery 
函数($){
//这里放置插件代码。
//无需返回任何内容,因为我们正在扩充jQuery对象
});
requirejs.config({
shim:{
jquery-cookie:[jquery]
}
});

我想知道我是否能做像jQuery这样的事情,就像这样:

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

或者这是使jQuery插件与requirejs兼容的唯一方法amd

解决方案

你只需要做什么

  define([jquery],//需要jquery 
函数($){
//这里放置插件代码。
//无需返回任何内容因为我们正在扩充jQuery对象
});

在jquery-cookie.js的末尾,或者

  requirejs.config({
shim:{
jquery-cookie:[jquery]
}
});

在包含jquery-cookie之前的任何地方(例如,数据主要指向的地方)。 / p>

您发布的最后一个代码块适用于jQuery等重新分配的内容,可能是也可能不在AMD环境中。理想情况下,每个jQuery插件都已经设置好了。



我更喜欢将包含的库保持为尽可能不掺杂,所以每页的全局shim配置就像对我来说最干净的解决方案。这样升级更安全,CDN成为可能。


I'm working with requirejs+jquery and i was wondering if there was a smart way to make a jQuery plugin work well with require.

For example i'm using jQuery-cookie. If i understood correctly i can create a file called jquery-cookie.js and inside do

define(["jquery"], // Require jquery
       function($){
// Put here the plugin code. 
// No need to return anything as we are augmenting the jQuery object
});
requirejs.config( {
    "shim": {
        "jquery-cookie"  : ["jquery"]
    }
} );

i wondered if i could do things like jQuery does, which is like this:

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

or if this is the only way to make jQuery plugins compatible with requirejs or any amd

解决方案

You only need to do EITHER

define(["jquery"], // Require jquery
       function($){
// Put here the plugin code. 
// No need to return anything as we are augmenting the jQuery object
});

at the end of jquery-cookie.js, OR

requirejs.config( {
    "shim": {
        "jquery-cookie"  : ["jquery"]
    }
} );

anywhere before you include jquery-cookie (like wherever data-main points to, for instance).

The last code block you've posted is good for things like jQuery which get redistributed and may or may not be in an AMD environment. Ideally every jQuery plugin would have that set up already.

I prefer to keep included libraries as unadulterated as possible, so the global shim config once per page seems like the cleanest solution to me. That way upgrades are safer and CDNs become a possibility.

这篇关于如何使用requirejs加载jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆