LoginSignup
12
12

More than 5 years have passed since last update.

atom-shell + jQuery の環境で jQuery が使えない場合の解決方法

Last updated at Posted at 2014-06-02

atom-shell + jQuery の問題点

atom-shell で実行されるウェブアプリで jQuery を使おうとしても、$jQueryundefined になってしまってそのままでは利用することができません。

jQuery のソースを読んでみると、

jquery.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 ) {

// ...途中省略...

if ( typeof noGlobal === strundefined ) {
    window.jQuery = window.$ = jQuery;
}
return jQuery;
}));

と、こんな感じに module.exports"object" の場合は module.exportsfactory(global, true) の戻り値を入れています。

atom-shell では、通常のブラウザで JavaScript を実行する場合と違って、 module.exports が利用できるので factory(global, true) が処理されます。

そして、 factory 関数では、第2引数が、 undefined ではない場合、 window.$window.jQueryjQuery オブジェクトを入れる処理をしてくれません。

このため atom-shell 上のウェブアプリで $ とか jQuery を使おうとしても undefined なので使えません。

解決方法

atom-shell で jquery.js を読み込むと、module.exports に jQuery が入ってきます。

なので、以下の様な JavaScript ファイルを作って、jquery.js のあとに読み込みます。

jquery_after.js
if (typeof module === "object" && module.exports) {
  window.$ = window.jQuery = module.exports;
  module.exports = {};
}

で、 Grunt 等でいろんな JavaScript ライブラリを concat するときに、こんな感じで、jquery.js の直後にくっつけちゃいます。

Gruntfile.coffee

# ...省略...

  concat:
    dist:
      files:
        'dist/js/vendor.js': [
          'bower_components/jquery/dist/jquery.js'
          'src/js/jquery_after.js'

          # 'bower_components/lodash/dist/lodash.js'
          # 'bower_components/sprintf/dist/sprintf.min.js'
          # とか、その他いろんなライブラリ
        ]

# ...省略...

Grunt 等使っていない場合は、jquery.js 読み込み後に jquery_after.js を読み込めば OK です。

これで、atom-shell で実行されるウェブアプリでも jQuery が使えるようになります。
やったあ!

こちらからは以上です。

12
12
2

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
12
12