LoginSignup
17
16

More than 5 years have passed since last update.

javascriptの簡易的なモジュール分割

Last updated at Posted at 2014-09-08

BrowserifyやRequire.jsを導入するレベルでもない、プロダクト依存のモジュールをさくっと分割する方法。

scriptA.js
(function(exports) {
    exports.nameOfModule = exports.nameOfModule || {};
    var module = exports.nameOfModule;

    // MethodA
    // ===========================================================
    module.nameOfMethodA = function() {
        module.nameOfMethodB();
    };

    // propertyA
    // ===========================================================
    module.propertyA = 'hogehoge';

})(this);
scriptB.js
(function(exports) {
    exports.nameOfModule = exports.nameOfModule || {};
    var module = exports.nameOfModule;

    // MethodB
    // ===========================================================
    module.nameOfMethodB = function() {
        console.log(module.propertyA);
    };

})(this);

上3行と下1行が共通部分。

window.nameOfModuleが展開されてグローバル空間からアクセスが可能。
モジュール中ではmodule.hogehogeでモジュール中の他のパーツの読み出しが可能。

モジュール内の処理はネームスペースがmodulethisだけで完結するので、頭使わなくていいかと。

順不同なのでgrunt-contrib-concatでまとめたりminifyuglyfyもご自由にどうぞ。


Browserifyも検討したんだけど、作っていたものはページごとにイニシャライズの部分が違うので、全部を一つにまとめてしまうと、巨大なjsファイルがいくつも出来上がりそうなのでやめておいた。

単純に使い方間違っているだけかもしれないけれど、プレコンパイルなjsのモジュール系実装はSPAではないと向いていないのではないかと思った。

17
16
1

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
17
16