Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ is not defined - using jQuery with electron.js

I know there are many known solutions to this. But not a single one works. I keep getting this error:

Uncaught Exception:
ReferenceError: $ is not defined
    at: .....

Please note that I am using the npm installation of jQuery (npm install jquery --save).

I tried doing this:

<script> 
    window.nodeRequire = require; 
    delete window.require;
    delete window.exports; 
    delete window.module; 
    window.$ = window.jQuery = require('jquery');
</script>

but still got the error.

Then I tried:

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

but this also did not work.

I tried it with a local file as well:

<script>window.$ = window.jQuery = require('./jquery-3.3.1.min.js');</script>

But once again, I get the dreaded "$ is not defined" error. Can someone please explain what is happening. I understand how these solutions should work but I don't understand why they do not work for me.

Here is my full HTML page in its current state:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>...</title>
  </head>
  <body>
    <h1>Test</h1>
    <div id = "test"></div>
    <script>window.$ = window.jQuery = require('./jquery-3.3.1.min.js'); 
   </script>

    <script>
      require('./renderer.js')
    </script>

  </body>
</html>

I started this project with the electron quick start at https://github.com/electron/electron-quick-start .

Thanks in advance.

Edit: Interestingly, the oauth library was interfering with jquery as well. But even after removing oauth, it still is broken.

like image 866
gkgkgkgk Avatar asked Jun 12 '26 14:06

gkgkgkgk


1 Answers

I've also done npm install jquery --save on my Electron project.

The way I have gotten jQuery to work is by requiring it in the <head> tag of my HTML before any of the other <script> tags.

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <!-- jQuery (Should be declared before other JS imports) -->
    <script>
      var $ = jQuery = require("jquery")
    </script>
    ...
    <script src="../node_modules/jquery/dist/jquery.slim.min.js"></script>
    <script src="../node_modules/popper.js/dist/umd/popper.min.js"></script>
    <script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    ...
  </head>
  <body>
    ....
  </body>
</html>

I needed to install jQuery for Bootstrap so I require it before declaring the script source import for jQuery, followed by other JS that I need.

EDIT After integrating electron-forge , the above solution no longer works for me. What does work is the solution mentioned here: https://stackoverflow.com/a/37480521/1392578

like image 67
Neil P. Avatar answered Jun 15 '26 03:06

Neil P.