7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

サーバーサイド(Node.js)とクライアントサイド(AMD/非AMD)共通のJSモジュールの定義

Last updated at Posted at 2013-08-09

昨日からこういう書き方してる。

math.js
(function (loader) {
    loader(function _commonDefine () {
        var math = {}; math.add = function () {
            return [].slice.apply(arguments).reduce(
                function (sum, val) {
                    return sum + val;
                }, 0);
        };

        return math;
    });
})(
// AMD RequireJS
    'function' === typeof define && difine.amd
  ? function _loader_for_requirejs (commonDefine) {
        define([], function () {
            return commonDefine();
        });
    }
// CommonJS NodeJS
  : 'undefined' !== typeof module && module.exports &&
    'function'  === typeof require
  ? function _loader_for_commonjs (commonDefine) {
        module.exports.math = commonDefine();
    }
// this === window
  : function _loader_for_window (commonDefine) {
        this.calcs || (this.calcs = {});
        this.calcs.math = commonDefine();
    }
);

上記の書き方で、依存モジュールが必要な場合は

incr.js
(function (loader) {
    loader(function _commonDefine (math) {
        var incr = {}; incr.increment = function (val) {
            return math.add(val, 1);
        };

        return incr;
    });
})(
// AMD RequireJS
    'function' === typeof define && difine.amd
  ? function _loader_for_requirejs (commonDefine) {
        define([ "path/to/math" ], function (math) {
            return commonDefine(math);
        });
    }
// CommonJS NodeJS
  : 'undefined' !== typeof module && module.exports &&
    'function'  === typeof require
  ? function _loader_for_commonjs (commonDefine) {
        var math = require("path/to/math").math;
        module.exports.incr = commonDefine(math);
    }
// this === window
  : function _loader_for_window (commonDefine) {
        if (! this.calcs || ! this.calcs.math)
            throw new Error('"window.calcs" or "window.calcs.math" not found');

        this.calcs.incr = commonDefine(this.calcs.math);
    }
);

冗長性高いので、ラッパーがほしいかもしれない

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?