美文网首页
Electron学习(4)解决在electron中使用jQuer

Electron学习(4)解决在electron中使用jQuer

作者: 叶小七的真命天子 | 来源:发表于2017-10-29 12:39 被阅读384次

    自己在学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时都要重新一遍上述代码,很繁琐。

    相关文章

      网友评论

          本文标题:Electron学习(4)解决在electron中使用jQuer

          本文链接:https://www.haomeiwen.com/subject/dkqypxtx.html