在设计JS库时,我应该使它与RequireJS/AMD兼容吗?

Mim*_*ght 10 javascript amd requirejs

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

据我所知,使您的代码更多或更少地符合RequireJS使得没有RequireJS就无法使用.那我为什么要那样做?

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

  • 有没有办法支持两者而不分叉/分支?我应该提供垫片代码吗?

  • 我能正确理解吗?

exp*_*nit 23

如果您只处理浏览器(而不是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;
    });
}
Run Code Online (Sandbox Code Playgroud)

可以在这里找到Knockout非常相似的片段:

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

请注意,jQuery采用命名模块方法,而knockout使用匿名模块.即使检测到AMD,jQuery也会离开$并jQuery进入全局命名空间,而在检测到AMD时,Knockout(可能还有许多其他人)不会在全局命名空间中放置任何东西.如这些问题所示,每种方法都有利有弊: