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


当前回答

刚刚遇到了同样的问题

NPM安装jquery

< >脚本窗口。$ = window。</script> . jQuery = require(' 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>

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

<!-- 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) 不要求节点集成为假

源在这里

您可以尝试以下代码:

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration:false,
        }
});
<script>
  delete window.module;
</script>

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

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

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