Electron: jQuery is not defined
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
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>
electron FAQ answer :
http://electron.atom.io/docs/faq/
I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.
Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module, exports, require. This causes problems for some libraries since they want to insert the symbols with the same names.
To solve this, you can turn off node integration in Electron:
// In the main process.
let win = new BrowserWindow({
webPreferences: {
nodeIntegration: false } });
But if you want to keep the abilities of using Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:
<head>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports; delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
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.