Electron学习(4)解决在electron中使用jQuery报错的问题

自己在学app模块的时候想测试下各种事件的效果,于是就引入了jQuery,想注册点击事件触发app的事件监听,但是当我引入jQuery之后,却报了错,表示$符未定义。

Uncaught ReferenceError: $ is not defined

后来百度了一下才知道,jQuery等新版本的框架,在Electron中使用普通的引入的办法会引发异常,原因是Electron默认启用了Node.js的require模块,而这些框架为了支持commondJS标准,当Window中存在require时,会启用模块引入的方式。找到了下面的两种解决办法:

1、去掉jQuery中的第一行代码中的模块引入判断代码:

!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}

将其改成

!function(a,b){b(a)}

2、使用Electron官方论坛提供的方法:

<head>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>

注意如果采用这种方法之后,在你需要导入node.js模块时,就必需采用nodeRequire,而不能使用require

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <h1>hello world</h1>
  <script>
    window.nodeRequire = require;
    delete window.require;
    delete window.exports;
    delete window.module;
  </script>
  <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <script>
      const remote = nodeRequire('electron').remote
      const win = remote.getCurrentWindow()
      $('h1').click(function () {
        win.close()
      });
  </script>
</body>
</html>

个人建议使用第一种方法,改一个jQuery原文件就可以了,如果采用第二种方法,则在每个页面引入jQuery时都要重新一遍上述代码,很繁琐。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容