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

查看:22
本文介绍了在设计 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?

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

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

可以从 Knockout 中找到一个非常相似的片段 这里:

And a very similar snippet from Knockout can be found here:

} 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:

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

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