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
Another way of writing <script>window.$ = window.jQuery = require('./path/to/jquery');</script>
is :
<script src="./path/to/jquery" onload="window.$ = window.jQuery = module.exports;"></script>
Just came across this same problem
npm install jquery --save
<script>window.$ = window.jQuery = require('jquery');</script>
worked for me
Just install Jquery with following command.
npm install --save jquery
After that Please put belew line in js file which you want to use Jquery
let $ = require('jquery')
If you are using Angular2 you can create a new js file with this code:
// jquery-electron.js
if ((!window.jQuery || !window.$) && (!!module && !!module.exports)) {
window.jQuery = window.$ = module.exports;
}
and put it right after jquery path, in .angular-cli.json:
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"assets/js/jquery-electron.js",
...
...
]
im building and Angular App with electron, my solution was the following:
index.html
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
angular.json
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
So Jquery gets loaded from angular.json if on browser, else if it is an electron builded app it will require module instead.
If you want to import jquery in index.html instead of importing from angular.json use the following solution:
<script src="path/to/jquery"></script>
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
As seen in https://github.com/atom/electron/issues/254 the problem is caused because of this code:
if ( typeof module === "object" && typeof module.exports === "object" ) {
// set jQuery in `module`
} else {
// set jQuery in `window`
}
The jQuery code "sees" that its running in a CommonJS environment and ignores window
.
The solution is really easy, instead of loading jQuery through <script src="...">
, you should load like this:
<script>window.$ = window.jQuery = require('./path/to/jquery');</script>
Note: the dot before the path is required, since it indicates that it's the current directory. Also, remember to load jQuery before loading any other plugin that depends on it.