electron初体验--项目安装配置、主进程、渲染进程、项目打包

1,234 阅读5分钟

1、 Electron 基本介绍

我们来看一下官方对Electron的定义:

  • Electron是一个使用 JavaScript、HTML 和 CSS 构建桌面应用程序的框架。
  • 嵌入 Chromium 和 Node.js 到 二进制的 Electron 允许您保持一个 JavaScript 代码代码库并创建 在Windows上运行的跨平台应用 macOS和Linux——不需要本地开发 经验。

官网链接

1.1 常见的桌面GUI工具介绍

名称语音优点缺点
QTC++跨平台、性能好、生态好依赖多,程序包大
PyQTPython底层集成度高、易上手授权问题
WPFC#类库丰富、扩展灵活只支持Windows,程序包大
WinFormC#性能好,组件丰富,易上手只支持Windows,UI差
SwingJava基于AWT,组件丰富性能差,UI一般
NW.jsJS跨平台性好,界面美观底层交互差、性能差,包大
ElectronJS相比NW发展更好底层交互差、性能差,包大
CEFC++性能好,灵活集成,UI美观占用资源多,包大
  • 底层依赖 + 调用:CEF、QT、Swing
  • UI美观:Electron(NW.js)、PyQT
  • 跨平台:Swing(JAVA)、PyQT(Python、C++)、Electron(前端)

技术是为业务服务的,选择合适的最重要!

1.2 安装

  1. 创建文件夹
mkdir my-electron-app && cd my-electron-app
npm init
  1. init初始化命令会提示您在项目初始化配置中设置一些值,有几条规则需要遵循:
  • entry point 应为 main.js.
  • author 与 description 可为任意值,但对于应用打包是必填项。

你的 package.json 文件应该像这样:

{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "Hello World!",
  "main": "main.js",
  "author": "",
  "license": "MIT"
}

然后,将 electron 包安装到应用的开发依赖中。

npm install --save-dev electron

ps:如果遇到安装慢的问题,请配置.npmrc文件

image.png

ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
  1. 添加辅助字段,快速启动electron命令
"start": "electron ."

image.png

1.3 各类配置

  1. 安装nodemon,监听文件的变化
npm install nodemon

配置

image.png

 "start": "nodemon --watch main.js --exec electron ."
  1. 添加 .gitignore 文件

.gitignore 文件可以指定哪些文件和目录应该在Git中不被跟踪。 建议您复制一份 GitHub 的 Node.js gitignore 模板 到您项目的根目录,以避免将 node_modules 文件夹提交到版本控制系统中。

  • 文件如下:
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

3.其他

image.png

  • windows所有的窗口,那么应用就自动退出了
  • macos 在MacOS下,当全部窗口关闭,点击 dock 栏图标,窗口再次打开,激活窗口

main.js文件

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

function createWindow () {
  // 创建浏览器窗口
  const win = new BrowserWindow(
    {
      width: 800,
      height: 600,
      // 自动隐藏菜单栏
      autoHideMenuBar: true,
      //x,y 用于配置窗口的位置
      // x: 0,
      // y: 0,
    }
  )
  // 加载index.html
  win.loadFile('./pages/index.html')

  // 打开开发者工具
  win.webContents.openDevTools()
}
// 当electron 完成初始化并准备好创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  createWindow()

  // 在MacOS下,当全部窗口关闭,点击 dock 栏图标,窗口再次打开,激活窗口
  app.on('activate', () => {
    // mac 系统窗口数量为0
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})



// 关闭所有窗口时退出应用 (Windows & Linux)
app.on('window-all-closed', () => {
  // 并且不是mac系统时,执行
  if (process.platform !== 'darwin') {
    app.quit()
  }
})



  1. 配置nodemon.json文件,让项目自动重启
{
  "restartable": "rs",
  "ignore": [
    ".git",
    "node_modules/**/node_modules"
  ],
 
  "watch": [
   "*.*"
  ],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,html,css"
}


image.png

2. 主进程与渲染进程

  1. 基本思想。 多看几遍,多理解 image.png

  2. 说明

image.png

image.png 3. 执行顺序

image.png 4. 数据传递

image.png

3. 进程通信

3.1 渲染进程->主进程通信(单向)

  1. 页面添加相关元素,render.js添加对应的脚本
  2. preload.js使用 ipcRenderer.send("信道", 参数)发送消息,与主进程进行通信。 image.png

3.2 渲染进程<->主进程通信(双向)

  1. 概述: 渲染进程通过ipcRenderer.invoke发送消息,主进程使用ipcMain.hanlde接收并处理消息。ipcRenderer.invoke的返回值是promise的实例

2.流程图思路如下

image.png

3.3 主进程到渲染进程

  1. 概述:主进程使用win.webContents.send发送消息,渲染进程通过ipcRenderer.on处理消息

image.png

4. 打包项目

  1. 安装打包器

打开 DOS窗口,cd 到你的项目目录下,输入下面命令,全局安装electron打包器

npm install electron-builder -D

image.png

配置package.json中进行相关配置,

image.png

ps:json 文件不支持注释,使用时请去掉所有注释,

{
  "name": "01-my-electron-app",//程序的应用名称
  "version": "1.0.0",//应用程序版本
  "description": "this is a electron demo",
  "main": "main.js",//应用程序的入口文件
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon  --exec electron .",//启动应用程序
    "build": "electron-builder"
  },
  "build": {
    "appId": "com.atguigu.video",//应用程序的唯一标识
    //打包windows平台安装包的具体配置
    "win": {
      "icon": "./icon.png",//桌面应用图标
      "target": [
        {
          "target": "nsis",//指定使用NISIZ 作为应用程序格式
          "arch": [
            "x64"//生成64位的安装包
          ]
        }
      ]
    },
    "nsis": {
      "oneClick": false,//设置为'false”使安装程序显示安装向导界面,而不是一键安装"
      "perMachine": true,// 允许每台机器安装一次,而不是每个用户都安装
      "allowToChangeInstallationDirectory": true//允许用户在安装过程中选择安装目录
    }
  },
  "author": "fy",
  "license": "ISC",
  "devDependencies": {
    "electron": "^31.0.2",
    "electron-builder": "^24.13.3"
  },
  "dependencies": {
    "nodemon": "^3.1.4"
  }
}

2.执行打包命令:

在根目录下执行打包命令:

image.png

结果

image.png