Skip to content

Instantly share code, notes, and snippets.

@uupaa
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save uupaa/2c1ea0c16992ce941eab to your computer and use it in GitHub Desktop.

Select an option

Save uupaa/2c1ea0c16992ce941eab to your computer and use it in GitHub Desktop.
WebModulePattern考察

WebModulePattern を以下の形にする。

moduleExporter の中で return しているのがポイント。

// WebModule.js

GLOBAL.WebModule = {
    exports: function(name, closure) {
        var alias = name in GLOBAL ? (name + "_") : name;
        var entity = alias in this ? this[alias]
                                   : this[alias] = closure(GLOBAL);

        if (typeof exports !== "undefined") {
            module["exports"] = entity;
        }
        return entity;
    }
};
// Foo.js

(function moduleExporter(name, closure) { // http://git.io/WebModule
"use strict";

return GLOBAL["WebModule"] ? GLOBAL["WebModule"]["exports"](name, closure)
                           : closure(GLOBAL);

})("Foo", function moduleClosure(global) {
"use strict";
function Foo() {}

return Foo;
});

return があることで、先頭行に一行追加することで、CommonJS や ES6::modules に対応可能になる

  • $ npm run cjs

    • module.exports = <CR> を追加し
    module.exports = 
    (function moduleExporter(name, closure) {
    return entity;
    }, "Foo", function moduleClosure(global) {
    return entity;
    });
  • $ npm run es6

    • export var FILE_NAME = <CR> を追加する
    export var Foo = 
    (function moduleExporter(name, closure) {
        return entity;
    }, "Foo", function moduleClosure(global) {
    return entity;
    });

実際に必要とされるのは ES6::Modules への将来への対応で、Common.js への対応は恐らく不要(WebModule.js でできるので)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment