问题:在使用Electron进行开发时,当你尝试使用任何需要jQuery的JS插件时,插件都找不到jQuery,即使你使用脚本标签加载在正确的路径中。

例如,

<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>

运行上面的代码是行不通的。实际上,打开DevTools,转到Console视图,然后单击<p>元素。你应该看到函数$没有定义或者类似的效果。


当前回答

2022年。这对我很管用。

安装JQuery

npm install jquery --save

使用script标签将jquery添加到index.html文件中。 src应该是你的node_modules文件夹中jquery的路径

    <script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"></script>

现在JQuery将可用/定义为$在你的渲染器进程(renderer.js文件)

其他回答

如https://github.com/atom/electron/issues/254所示,问题是由以下代码引起的:

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

jQuery代码“看到”它在CommonJS环境中运行,并忽略了window。

解决方案真的很简单,而不是通过<script src="…>,你应该这样加载:

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

注意:路径前的点是必需的,因为它表示它是当前目录。另外,请记住在加载依赖jQuery的任何其他插件之前加载jQuery。

我也面临着同样的问题,这对我来说很有效!

使用npm安装jQuery

$ npm install jquery

然后以以下方式之一包含jQuery。

使用脚本标记

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

使用巴别塔

import $ from 'jquery';

使用Webpack

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

在jquery导入之前,你就可以开始了。更多信息请点击这里。

你可以把node-integration: false放在BrowserWindow的选项里面。

例如:window = new BrowserWindow({'node-integration': false});

2022年。这对我很管用。

安装JQuery

npm install jquery --save

使用script标签将jquery添加到index.html文件中。 src应该是你的node_modules文件夹中jquery的路径

    <script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"></script>

现在JQuery将可用/定义为$在你的渲染器进程(renderer.js文件)