问题:在使用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>元素。你应该看到函数$没有定义或者类似的效果。


当前回答

在我看来,更好、更通用的解决方案是:

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

好处

适用于浏览器和电子具有相同的代码 修复了所有第三方库(不仅仅是jQuery)的问题,而无需指定每个库 脚本构建/打包友好(即Grunt / Gulp所有脚本到vendor.js) 不要求节点集成为假

源在这里

其他回答

如果你使用的是Angular2,你可以用下面的代码创建一个新的js文件:

// jquery-electron.js

if ((!window.jQuery || !window.$) && (!!module && !!module.exports)) {
      window.jQuery = window.$ = module.exports;
}

然后把它放在。angular-cli.json的jquery路径后面:

"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "assets/js/jquery-electron.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。

我用电子构建和Angular应用程序,我的解决方案如下:

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

Jquery从angular加载。Json如果在浏览器上,否则如果它是一个电子构建的应用程序,它将需要模块代替。

如果你想在index.html中导入jquery,而不是从angular. html中导入。Json使用以下解决方案:

<script src="path/to/jquery"></script>
<script>
    if ( typeof module === "object" && typeof module.exports === "object" ) {
      window.$ = window.jQuery = require('jquery');
    }
</script>
<script>
  delete window.module;
</script>

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

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文件)