Learn how to use without problems jQuery in your electron app.


Believe it or not, you'll be not able to use jQuery at first time if you include simply the jQuery script file into your document (at less till the date using jQuery 3.0). If you do it, the first message that you'll find in your console will be :

Uncaught ReferenceError : $ is not defined
# or
Uncaught ReferenceError : jQuery is not defined

And you may get frustrated trying to solve it by yourself as you may need to read the source code of jQuery to know why it's failing.

jQuery isn't defined (globally in the window) because "module" is defined, therefore you can't access the jQuery variable as it doesn't exists really, this problem is caused by the following if statement in the library :

if ( typeof module === "object" && typeof module.exports === "object" ) {
  // set jQuery in `module`
} else {
  // set jQuery in `window`
}

Remember that Electron uses node to work, therefore jQuery has a conflict in the declaration due to module, the no-recommended solution is to set the node-integration property to false in BrowserWindow(), however that would remove the use of node in your app and nobody wants that ... i think.

But don't worry, the real solution is more simple than you think and you'll be able to use jQuery normally in a couple of seconds.

Fix with NPM

Install jQuery into your project using the following command in the node command prompt :

npm install jquery --save

Now add the following code inside a script tag (or a js file):

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

You need to simply declare the jQuery and $global variables with the value (the library itself) returned for the require method.

Fix with jQuery library file

If you don't install directly the jQuery library with NPM, that means you have simply the jQuery file somewhere in your project. To add the jQuery variable in the window, use require with the path to the jQuery library as first parameter :

<!-- If the require doesn't work, include first the jQuery file
<script src="jquery-3.0.0.min.js"></script>-->
<script>window.$ = window.jQuery = require('./jquery-3.0.0.min.js');</script>

You need to simply declare the jQuery and $ global variables with the value (the library itself) returned for the require method.

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors