避免 IIFE 模式的多个副本

Avoiding Multiple Copies of the IIFE Pattern

我看到了以下 IIFE 模式(它有名字吗?),根据 this 博客 post 可以防止其他插件,改进缩小并具有 tiny 性能优势。我还亲自给 IIFE 添加了一个命名空间:

(function (MyNamespace, $, window, document, undefined) {
    "use strict";

    // My Code

})(window.MyNamespace = window.MyNamespace || {}, window.jQuery, window, document);

我在每个 JavaScript 文件中都看到过这种模式。连接和缩小之后呢?我怎样才能确保我的代码只包含上述 IIFE 中的 一个 ? NPM、Gulp/Grunt 等工具在这方面有帮助吗?是否有处理这种情况的标准方法?

经过一些调查,像 jQuery 和 knockout 这样的库编写者通过在 JavaScript 上预先挂起和附加 IFFE 来处理这个问题。然后他们有一个将所有内容连接在一起的 make 文件。

jQuery IIFE 的启动处理非浏览器场景要复杂得多。

jQuery intro.js

(function( global, factory ) {
    if ( typeof module === "object" && typeof module.exports === "object" ) {
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    } else {
        factory( global );
    }
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

jQuery outro.js

return jQuery;
}));

Knockout(感谢@JamesThorpe)采用了一种略微不同的方法来解析 window 及其后代。

Knockout extern-pre.js

(function(undefined){
    var window = this || (0, eval)('this'),
        document = window['document'],
        navigator = window['navigator'],
        jQueryInstance = window["jQuery"],
        JSON = window["JSON"];

Knockout extern-post.js

}());

然后您可以使用 gulp-concat 之类的东西将介绍和结尾文件夹在您自己的脚本文件周围。