atom-shell + jQuery の問題点
atom-shell で実行されるウェブアプリで jQuery を使おうとしても、$ や jQuery が undefined になってしまってそのままでは利用することができません。
jQuery のソースを読んでみると、
(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.exports に factory(global, true) の戻り値を入れています。
atom-shell では、通常のブラウザで JavaScript を実行する場合と違って、 module.exports が利用できるので factory(global, true) が処理されます。
そして、 factory 関数では、第2引数が、 undefined ではない場合、 window.$ と window.jQuery に jQuery オブジェクトを入れる処理をしてくれません。
このため atom-shell 上のウェブアプリで $ とか jQuery を使おうとしても undefined なので使えません。
解決方法
atom-shell で jquery.js を読み込むと、module.exports に jQuery が入ってきます。
なので、以下の様な JavaScript ファイルを作って、jquery.js のあとに読み込みます。
if (typeof module === "object" && module.exports) {
window.$ = window.jQuery = module.exports;
module.exports = {};
}
で、 Grunt 等でいろんな JavaScript ライブラリを concat するときに、こんな感じで、jquery.js の直後にくっつけちゃいます。
# ...省略...
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 が使えるようになります。
やったあ!
こちらからは以上です。