一、Electron 环境初步搭建

新建一个文件夹,然后进行 npm init -y 进行初始化,然后我们在进行 npm i electron --save-dev   , 此时我们按照官网的教程进行一个初步的搭建,

  • 1.在 package.json 文件进行修改
{
  "name": "electron-ui",
  "version": "1.0.0",
  "description": "electron app!",
  "main": "main.js",
  "author": "He Ming",
  "license": "ISC",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^30.1.0"
  }
}
  • 新建 main.js  文件

在 main.js 文件中我们需要进行初步搭建 

  •  引入 electron 
const { app, BrowserWindow } = require('electron')
  • 创建启动执行之后的窗口

在创建启动执行窗口我们需要进行搭建,

whenReady:返回的是一个 Promise 我们在then里面进行窗口实例创建 

loadFile : 窗口加载页面

on: 监听窗口关闭事件

     生命周期事件

app.whenReady().then(() => {
  const mainWin = new BrowserWindow({
    width: 600,
    height: 600,
  })


  // 窗口加载页面
  mainWin.loadFile('index.html')

  // 监听窗口
  mainWin.on('closed', () => {
    // mainWin = null
  })
})
  • 监听所有窗口都关闭

此次监听窗口关闭的是所有的窗口关闭事件,

// 监听所有窗口都关闭
app.on('window-all-closed', () => {
  // macOS 下,当关闭所有窗口时,应用不会退出
  if (process.platform !== 'darwin') {
  // 调用退出事件
    app.quit()
  }
})

完整代码 

  •  mian.js
const { app, BrowserWindow } = require('electron/main')
const path = require('node:path')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  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()
  }
})
  •   preload.js
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const type of ['chrome', 'node', 'electron']) {
    replaceText(`${type}-version`, process.versions[type])
  }
})
  • 新建 index.html  文件
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>桌面应用</title>
</head>

<body>
  <h1>桌面级应用</h1>
</body>

</html>

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-11 04:26:01       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-11 04:26:01       5 阅读
  3. 在Django里面运行非项目文件

    2024-06-11 04:26:01       4 阅读
  4. Python语言-面向对象

    2024-06-11 04:26:01       7 阅读

热门阅读

  1. C++线程

    2024-06-11 04:26:01       16 阅读
  2. HOT100与剑指Offer

    2024-06-11 04:26:01       21 阅读
  3. 游戏心理学Day10

    2024-06-11 04:26:01       14 阅读
  4. 使用EFCore和Linq查询语句封装复杂的查询结果

    2024-06-11 04:26:01       20 阅读
  5. Python爬虫实现“自动重试”机制的方法(1)

    2024-06-11 04:26:01       13 阅读
  6. OpenAI 发布的 GPT-4o是什么,有什么功能?

    2024-06-11 04:26:01       18 阅读