在设计JS库时,我应该让它与RequireJS/AMD兼容还是不兼容

When designing a JS library should I make it RequireJS/AMD compatible or not?

本文关键字:AMD RequireJS 不兼容 JS 库时 我应该      更新时间:2023-09-26

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

据我所知,让你的代码或多或少符合RequireJS会让你在没有RequireJS的情况下无法使用。那我为什么要这么做呢?

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

  • 有没有一种方法可以在不分叉/分支的情况下同时支持这两者?我应该提供填充码吗?

  • 我理解正确吗?

如果您只处理浏览器(而不是node.js),那么只有几行代码可以使库同时支持AMD和非AMD。

例如,以下是jQuery中执行此操作的文件,除四个文件外,其余文件都是注释:

// 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非常相似的片段:

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

请注意,jQuery采用命名模块的方法,而knockout则使用匿名模块。jQuery还将$jQuery留在全局命名空间中,即使检测到AMD也是如此,而Knockout(可能还有许多其他)在检测到AMD时不会将任何内容放入全局命名空间中。每种方法都有利弊,如以下问题所示:

  • 用require.js实现jQuery的正确方法
  • 将ScriptSharp与Knockout一起使用。通过RequireJS进行映射