phi

I'm a Game Programmer and Frontend Engineer passionate about programming education. Math / C / C++ / C# / JavaScript / HTML5 / CSS3 / Python

phiaryjust a creator

Electron で jQuery をスマートに読み込む方法

10 years ago

Electron で $ ないって言われるんだけど...

Electron で普通に jQuery を使おうとすると, 下記のようなエラーが表示されます.

Uncaught ReferenceError: $ is not defined  

jQuery を上手く読み込めないわけですね.

jQuery を覗いてみる

この原因は jQuery の実装コードにありました.

jquery.js

(function( global, factory ) {

    if ( typeof module === "object" && typeof module.exports === "object" ) {
        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // e.g. var jQuery = require("jquery")(window);
        // See ticket #14549 for more info.
        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 );
    }

// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
  ...
});

まぁ要は Electron 上で html ファイルを開いた場合, modulemodule.exports が存在するので Node.js 用のモジュール方式で読み込んでしまうわけです.

ネットに転がってるあるある解決法

そこでネット上にごろごろ転がっている対策法を見てみると下記の方な方法でした.

<script>  
window.jQuery = window.$ = require('./lib/jquery');  
</script>  

安易すぎます... これだと Electron に最適化されちゃって Web 上では動かなくなってしまいます.

無理やりでもいいから script タグ使って動かしたいよね

そこで本題です. jQuery 読み込む前に無理やり module.exports を空にして,
jQuery 読み込んだ後に復帰させれば Web 上でも Electron 上でも動くやんってことで

<script>  
// for electron
if (typeof module !== 'undefined') {  
  window.__tempModuleExports__ = module.exports;
  module.exports = false;
}
</script>  
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js'></script>  
<script>  
// for electron
if (window.__tempModuleExports__) {  
  module.exports = window.__tempModuleExports__;
  window.__tempModuleExports__ = null;
  delete window.__tempModuleExports__;
}
</script>

<script>  
$(function() {
  console.log($ !== undefined);
});
</script>  

これで無事解決♪

もっとスマートな良い解決策が...

このエントリー書いてる途中で知ったんですが, BrowserWindow をインスタンス化する際のオプションで node-integration ってのがあるらしく これを false にすれば module のない状態で Web ページを開けるとのこと...

mainWindow = new BrowserWindow({width: 800, height: 600, 'node-integration': false});  

この方法だったら html 側も汚さず jQuery を読み込めますね♪ 最初にこの方法知りたかった...