Electron: jQuery is not defined

Bruno Vaz picture Bruno Vaz · Sep 17, 2015 · Viewed 144k times · Source

Problem: while developing using Electron, when you try to use any JS plugin that requires jQuery, the plugin doesn't find jQuery, even if you load in the correct path using script tags.

For example,

<body>
<p id="click-me">Click me!</p>
...
<script src="node_modules/jquery/dist/jquery.min.js"></script> //jQuery should be loaded now
<script>$("#click-me").click(() => {alert("Clicked")});</script>
</body>

Running this code above wouldn't work. In fact, open up DevTools, go to the Console view, and click on the <p> element. You should see that function $ is not defined or something to that effect.

Answer

Dale Harders picture Dale Harders · May 27, 2016

A better and more generic solution IMO:

<!-- Insert this line above script imports  -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>

<!-- normal script imports etc  -->
<script src="scripts/jquery.min.js"></script>    
<script src="scripts/vendor.js"></script>    

<!-- Insert this line after script imports -->
<script>if (window.module) module = window.module;</script>

Benefits

  • Works for both browser and electron with the same code
  • Fixes issues for ALL 3rd-party libraries (not just jQuery) without having to specify each one
  • Script Build / Pack Friendly (i.e. Grunt / Gulp all scripts into vendor.js)
  • Does NOT require node-integration to be false

source here