在设计JS库时,我应该使它与RequireJS/AMD兼容吗? [英] When designing a JS library should I make it RequireJS/AMD compatible or not?

查看:77
本文介绍了在设计JS库时,我应该使它与RequireJS/AMD兼容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要制作一个通用的JavaScript库,应该如何处理RequireJS支持?

If I'm making a JavaScript library for general use, how should I handle RequireJS support?

据我所知,使您的代码或多或少与RequireJS兼容使得没有RequireJS就无法使用.那我为什么要这么做呢?

As far as I can tell, making your code compliant with RequireJS more or less makes it impossible to use without RequireJS. So why would I do that?

  • 没有要求的人如何使用此代码?

  • How do people without Require use this code?

是否有一种无需分叉/分支即可支持这两者的方法?我应该提供填充代码吗?

Is there a way to support both without forking / branching? Should I provide the shim code?

我正确理解了吗?

推荐答案

如果您只使用浏览器(而不是node.js),则使该库支持AMD和非AMD的只有几行.

If you're only dealing with browser (not node.js), it's only a handful of lines to make the library support both AMD and non-AMD.

例如,这是jQuery中的文件,其中只有四个是注释:

For example, here is the file from jQuery that does it, of which all but four are comments:

// Execute the factory to produce jQuery
var jQuery = factory( window );

// 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;
    });
}

可以找到这里:

} else if (typeof define === 'function' && define['amd']) {
    // [2] AMD anonymous module
    define(['exports'], factory);
}

请注意,当淘汰赛使用匿名模块时,jQuery采用命名模块的方法. jQuery还将$jQuery保留在全局名称空间中,即使检测到AMD ,而当检测到AMD时,Knockout(可能还有许多其他)确实将任何内容放入全局名称空间.这些问题说明了每种方法的利弊:

Note that jQuery takes the named module approach while knockout uses an anonymous module. jQuery also leaves $ and jQuery in the global namespace, even when AMD is detected, whereas Knockout (and probably many others) do not put anything in global namespace when AMD detected. There are pros and cons to each approach, as illustrated by these questions:

  • Correct way to implement jQuery with require.js
  • Using ScriptSharp with Knockout.Mapping through RequireJS

这篇关于在设计JS库时,我应该使它与RequireJS/AMD兼容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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