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運行成功。

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