搭建electron开发环境

electron是使用js,html,css构建桌面端应用程序的框架,可以使用electron开发Windows和Mac端应用。

安装nodejs,npm,cnpm

首先需要安装nodejs,npm和cnpm,安装后在命令行输入 node -v 和npm -v,如果输出了版本号,说明已经正常安装。

输入命令安装cnpm,cnpm下载三方库的速度会更快。

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

安装electron

cnpm install -g electron

输入命令electron -v,如果输出了版本号,说明electron已经安装成功。

新建工程

新建目录命名为electronDemo,使用npm init -y 新建一个前端工程,在package.json中增加一行"main": “main.js”,这行代表应用程序的入口是main.js文件。

{
    
    
  "name": "electronDemo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    
    
    "electron": "^22.1.0"
  }
}

在electronDemo目录中新建index.html文件,在body中增加了hello, electron!这行文本。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    hello, electron!
</body>
</html>

在electronDemo目录中新建main.js文件,在main.js文件增加内容

const {
    
     app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
    
    
  const win = new BrowserWindow({
    
    
    width: 800,
    height: 600
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
    
    
  createWindow()

  app.on('activate', () => {
    
    
    if (BrowserWindow.getAllWindows().length === 0) {
    
    
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
    
    
  if (process.platform !== 'darwin') {
    
    
    app.quit()
  }
})

app.whenReady()是app启动后的Promise,使用then可以监听对应的状态,在这个回调里面增加createWindow函数,createWindow新建了一个浏览器窗口,设置宽高,并且使用浏览器窗口加载index.html文件。

在终端运行npm run start命令,electron应用的窗口可以正常弹出。

请添加图片描述

调试工程

electron应用在运行时有两个进程分别是渲染进程和主进程。如果是调试网页代码,在macOS上可以直接使用快捷键,Option+Command+I,即可唤起调试界面。

如果要调试main.js中代码,需要使用VSCode打开工程,点击左侧debug菜单,创建launch.json文件。

{
    
    
  "version": "0.2.0",
  "configurations": [
    {
    
    
      "name": "Debug Main Process",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
      "windows": {
    
    
        "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
      },
      "args" : ["."]
    }
  ]
}

在main.js文件app.whenReady()的回调中增加一个断点,点击debug区域的启动程序按钮,断点可以正常执行。

猜你喜欢

转载自blog.csdn.net/u011608357/article/details/128792824