Electron配置jquery

Electron使用纯 JavaScript 语法来调用丰富的原生(操作系统) APIs,从而创建桌面应用。所以,很多 JavaScript 的成熟工具和框架都可以在Electron中配置,例如,我们经常使用的 jquery 。

安装jquery

在我们的Electron项目的根目录下,执行如下命令,来安装jquery的依赖。

npm install jquery --save

这个时候的 package.json 的 dependencies 就会增加jquery的依赖配置。

{
  "name": "demo",
  "version": "1.0.0",
  "description": "a Electron Demo Application",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Woods",
  "license": "ISC",
  "devDependencies": {
    "electron": "^9.1.0",
    "electron-reloader": "^1.0.1"
  },
  "dependencies": {
    "jquery": "^3.5.1"
  }
}

使用jquery

修改我们的index.html文件,增加jquery的引用,代码如下:

<script>
	window.$ = window.jQuery = require('./node_modules/jquery/dist/jquery.min.js');
</script>

这样,我们就可以在index.html中使用jquery了。例如,用 jquery 配置按钮的点击事件。

index.html修改后如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    <input type="button" id="btn" value="测试"> 

    <script>
      window.$ = window.jQuery = require('./node_modules/jquery/dist/jquery.min.js');
      // require('./node_modules/bootstrap/dist/js/bootstrap.min.js');
    </script>
    <script>
      $("#btn").click(function(){
        alert("button is clicked.");
      });
    </script>
  </body>
</html>

然后,我们用命令 npm start 启动项目,点击页面上的"测试"按钮后,就会看到弹出框提示了,说明jquery运行成功。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章