Electron安裝和HelloWorld程序源碼解釋

注1:推薦閱讀Electron官方API文檔:https://www.w3cschool.cn/electronmanual/p9al1qkx.html
遇到問題可以參考我的博客/留言,我會盡力幫忙解決

安裝Electron

首先,你要安裝node環境
之後,
命令行輸入

npm install cnpm -g  --registry=https://registry.npm.taobao.org
cnpm install electron -g

第一句是安裝淘寶鏡像cnpm
第二句安裝electron

安裝Hello World項目

# 克隆這倉庫
$ git clone https://github.com/electron/electron-quick-start
# 進入倉庫
$ cd electron-quick-start
# 安裝依賴庫並運行應用
$ npm install && npm start

hello world程序講解

關於json文件

json文件是類似於xml但是更輕量的一種數據傳輸文件
一切皆對象,註釋本身也是對象
例如

{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "repository": "https://github.com/electron/electron-quick-start",
  "keywords": [
    "Electron",
    "quick",
    "start",
    "tutorial",
    "demo"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "^7.1.6"
  }
}

VScode調試main.js(主進程)

折騰良久,終於明白怎麼弄了
官方提供的調試方法大家可以先去嘗試,使用chrome很方便,但是不知道爲什麼我的chrome無法捕獲main打開的進程
所以就只能使用vscode來調試了。
首先打開main.js
F5調試會自動生成launch.json,這個配置文件指出nodejs運行時引用的electron文件,我的配置如下:

{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Debug Main Process",
        "type": "node",
        "request": "launch",
        "cwd": "${workspaceRoot}",
        "runtimeExecutable": "C:/Users/Administrator/AppData/Roaming/npm/electron.cmd",//這裏是electron.cmd所在路徑
        "windows": {
          "runtimeExecutable": "C:/Users/Administrator/AppData/Roaming/npm/electron.cmd"
        },
        "args" : ["."],
        "program": "C:/Users/Administrator/Desktop/electron_modules/electron-quick-start/main.js",//這裏是項目主進程文件所在路徑
        "protocol": "inspector" //添加默認的協議是legacy,這個協議導致不進入斷點

      }
    ]
  }

調試渲染進程

運行main.js之後,在窗口中打開View,打開toggle developer tool(開關開發者工具)
然後就可以打開V8提供的開發者工具調試渲染進程了
也可以在主進程中直接打開,見main.js代碼

關於主進程和渲染進程

主進程
在 Electron 裏,運行 package.json 裏 main 腳本的進程被稱爲主進程。在主進程運行的腳本可以以創建 web 頁面的形式展示 GUI。

渲染進程
由於 Electron 使用 Chromium 來展示頁面,所以 Chromium 的多進程結構也被充分利用。每個 Electron 的頁面都在運行着自己的進程,這樣的進程我們稱之爲渲染進程。

在一般瀏覽器中,網頁通常會在沙盒環境下運行,並且不允許訪問原生資源。然而,Electron 用戶擁有在網頁中調用 io.js 的 APIs 的能力,可以與底層操作系統直接交互。

主進程與渲染進程的區別
主進程使用 BrowserWindow 實例創建網頁。每個 BrowserWindow 實例都在自己的渲染進程裏運行着一個網頁。當一個 BrowserWindow 實例被銷燬後,相應的渲染進程也會被終止。

主進程管理所有頁面和與之對應的渲染進程。每個渲染進程都是相互獨立的,並且只關心他們自己的網頁。

由於在網頁裏管理原生 GUI 資源是非常危險而且容易造成資源泄露,所以在網頁面調用 GUI 相關的 APIs 是不被允許的。如果你想在網頁裏使用 GUI 操作,其對應的渲染進程必須與主進程進行通訊,請求主進程進行相關的 GUI 操作。

在 Electron,我們提供用於在主進程與渲染進程之間通訊的 ipc 模塊。並且也有一個遠程進程調用風格的通訊模塊 remote。

hello world源碼和翻譯解釋

helloworld主進程和註解
main.js

// Modules to control application life and create native browser window
//模塊控制應用程序生命週期和創建本地瀏覽器窗口
const {app, BrowserWindow} = require('electron')
//const 聲明一個只讀的常量,一旦聲明,就無法修改它的值
const path = require('path')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
//保持窗口對象的全局引用,如果你不這樣做,窗口將會
//在JavaScript對象被垃圾回收時自動關閉。
let mainWindow

function createWindow () {
  // Create the browser window.
  //創建瀏覽器窗口。
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
      //指定將在頁面中運行其他腳本之前加載的腳本。
      //無論節點集成是打開還是關閉,這個腳本都可以訪問節點api。這個值應該是腳本的絕對文件路徑。
      //當關閉節點集成時,預加載腳本可以將節點全局符號重新引入全局範圍。
    }
  })

  // and load the index.html of the app.加載index網頁
  mainWindow.loadFile('index.html')

  // Open the DevTools.通過這一句可以直接打開V8的渲染進程調試工具
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  //當窗口關閉時執行函數
  mainWindow.on('closed', function () {
    // Dereference(廢棄) the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    //取消對窗口對象的引用,通常會存儲窗口
    //如果你的應用程序支持多窗口,你應該在這裏刪除相應的元素。
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
//這個方法將在electron完成時被調用
//初始化,準備創建瀏覽器窗口。
//有些api只能在此事件發生後使用。
app.on('ready', createWindow)

// Quit when all windows are closed.當所有窗口關閉時退出
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd  + Q
  //在macOS中保持窗口的活動狀態直到用戶使用Cmd  + Q退出
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  //沒看懂
  if (mainWindow === null) createWindow()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
//你可以在這裏寫入剩餘的主進程,或者引入其它文件中的主進程

index頁面

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <--以上兩句是安全策略,引入外部js文件注意註釋掉-->
    <title>Hello World!</title>
  </head>
  <body>
    <div>
      <h2>Process</h2>
      <button onclick="getProcessInfo()">查看process信息</button>
    </div>
    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>

渲染進程

// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
//這個文件是index.html文件所需要的
//在窗口的渲染過程中執行。
//在這個過程中沒有可用的Node.js api,因爲
//“nodeIntegration”被關閉了,使用“preload”。js”
//有選擇地啓用渲染中需要的特性
function getProcessInfo(){
    console.log("getCPUUSEAGE")
}
發佈了136 篇原創文章 · 獲贊 14 · 訪問量 5812
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章