为什么我不能在 Electron 中使用脚本标签引用 jQuery?

Why can't I reference jQuery using a script tag in Electron?

在 nodejs electron 应用程序中使用 jquery。我必须通过 npm 安装 jQuery 并使用 require('jquery') 来引用 jQuery

它工作正常。

我需要知道为什么我不能像在普通浏览器中那样使用脚本标签附加 jquery

<script src="jquery-1.12.1.min.js"></script> //getting error $ not defined

下面的代码仅使用附加的脚本标签 jquery,出现错误,$ 未定义

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.12.1.min.js"></script>
    <!--<script>-->
        <!--var $ = require('jquery');-->
    <!--</script>-->
    <script>
        $(document).ready(function(){});
    </script>
    <link href="style.css" rel="stylesheet">
</head>

<body>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum vel, ipsum nisi laboriosam nesciunt. Asperiores dolorum tempore quia, voluptatum laborum dolore officiis velit similique amet totam in? At, neque, assumenda.</p>
</body>

</html>

如果您在 Electron 应用程序中尝试这样做,那么很可能是 Jquery 文件不在指定的路径中。它很可能位于 /node_modules/Jquery/... 之类的地方。尝试绝对路径。或者,如果主机连接到 Internet,您应该可以使用 Jquery CDN。

这似乎是 Electron 中的一个已知问题,

Here #254

如前所述,jQuery 试图变得聪明并确定它是在浏览器中还是在 node.js 环境中。在浏览器中,它会定义 $jQuery,但在 node.js 环境中,它会尝试通过将其分配给 module.exports.

来导出其主要对象

由于渲染器进程有 node.js(和 module)可用 jQuery 错误地假设它包含在 require 中。

因此,作为解决方法,您可以使用类似这样的方法:

<script src="path/to/jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript"> jQuery = $ = module.exports </script>