The web front-end project uses electron to package into a cross-platform desktop program (Windows)

What is Electron?

Electron is a framework for building desktop applications using JavaScript, HTML, and CSS. Embedding Chromium and Node.js into the Electron binary allows you to maintain a JavaScript code base and create cross-platform applications that run on macOS and Linux—no local development experience required.

quick start

Basic usage requirements

Before developing with Electron, you need to have Node.js installed. We recommend that you use the latest LTS version.
Check the locally installed node version and npm version:

node -v
npm -v

insert image description here
The front-end project packaged this time is developed using vue, check the vue version

vue -V

insert image description here

Download an open source project from github

Use Vue to develop PC-side web front-end projects
(Angular, React, Vue or pure HTML+CSS+JavaScript are all available)
use VSCode to open the project, execute npm install to download the project dependency package
insert image description here

npm install

insert image description here

Execute the startup script to run the project

View the project package.json package to view the script
insert image description here
Execute npm run dev to start the project

npm run dev

Start error:
insert image description here

  • Reason: OpenSSL3.0 released by node V17 has stricter restrictions on the algorithm and key size, and this error will occur in versions after node V17 (including)
  • Solution: willSET NODE_OPTIONS=–openssl-legacy-providerAdd it to the vue script in package.json. If you only need to start the project, you only need to add it before the startup script.
    insert image description here
    Execute npm run dev again
npm run dev

insert image description here
insert image description here

Install electron dependency package

Before installation:

{
    
    
  "name": "manage-desk",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    
    
    "dev": "SET NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "SET NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "SET NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
  },
  "dependencies": {
    
    
    "@jiaminghi/data-view": "^2.3.8",
    "core-js": "^2.6.5",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    
    
    "@vue/cli-plugin-babel": "^3.11.0",
    "@vue/cli-plugin-eslint": "^3.11.0",
    "@vue/cli-service": "^3.11.0",
    "@vue/eslint-config-standard": "^4.0.0",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    
    
    "root": true,
    "env": {
    
    
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "@vue/standard"
    ],
    "rules": {
    
    },
    "parserOptions": {
    
    
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    
    
    "plugins": {
    
    
      "autoprefixer": {
    
    }
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

npm install --save-dev electron//只需要在开发环境安装即可

insert image description here

Write the electron entry file, configure the entry file path and electron execution script in package.json

  • Create a new electron folder, create the main.js file as the entry file, the file name can be written freely, just specify the main field in package.json
const {
    
     app, BrowserWindow } = require('electron');

// 该方法创建一个窗口
const createWindow = () => {
    
    
    // 初始化浏览器窗口设置参数
    const win = new BrowserWindow({
    
    
      width: 1500,
      height: 800,
      minWidth:1200,
      minHeight:600
    })
    // 加载页面
    win.loadURL('http://localhost:8080');
  }


//在 Electron 中,只有在 app 模块的 ready 事件被激发后才能创建浏览器窗口。您可以通过使用 app.whenReady() API来监听此事件。在whenReady()成功后调用createWindow()。
  app.whenReady().then(() => {
    
    
    createWindow()
    // 当 Linux 和 Windows 应用在没有窗口打开时退出了,macOS 应用通常即使在没有打开任何窗口的情况下也继续运行,并且在没有窗口可用的情况下激活应用时会打开新的窗口。
    // 为了实现这一特性,监听 app 模块的 activate 事件。如果没有任何浏览器窗口是打开的,则调用 createWindow() 方法。
    // 因为窗口无法在 ready 事件前创建,你应当在你的应用初始化后仅监听 activate 事件。 通过在您现有的 whenReady() 回调中附上您的事件监听器来完成这个操作。
    app.on('activate', () => {
    
    
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  })
// 窗口全部关闭时执行退出APP
  app.on('window-all-closed', () => {
    
    
    // 虽然你现在可以打开一个浏览器窗口,但你还需要一些额外的模板代码使其看起来更像是各平台原生的。 应用程序窗口在每个OS下有不同的行为,Electron将在app中实现这些约定的责任交给开发者们。
    // 一般而言,你可以使用 进程 全局的 platform 属性来专门为某些操作系统运行代码。
    // 在Windows和Linux上,关闭所有窗口通常会完全退出一个应用程序。
    // 为了实现这一点,你需要监听 app 模块的 'window-all-closed' 事件。如果用户不是在 macOS(darwin) 上运行程序,则调用 app.quit()。
    if (process.platform !== 'darwin') app.quit()
    
    console.log("window-all-closed:窗口全部关闭,程序退出!");
  })

insert image description here

Start the electron script and run the electron application

npm run start

Electron opens an independent window, which is essentially a browser window. Electron renders web pages through the rendering process, runs main.js through the main process, and hands over the codes that interact with the local, such as obtaining Bluetooth device information, to the main process for execution
insert image description here
. A sentence is printed during the closing time of monitoring all windows:

insert image description here
Chinese garbled solution: modify the electron startup script

"start": "chcp 65001 && electron ."

insert image description here

Application Packaging Windows Platform

Install electron-builder

npm install electron-builder  --save-dev

insert image description here

Electron packaging configuration

Add build top-level key configuration build configuration in package.json

 //electron打包构建配置
 "build": {
    
    
    "copyright":"Copyright © 2023",
    "directories"
          "output":"./output-electron"//打包输出目录
    },
    "win":{
    
    //打包win程序包的配置
          "target": [
            {
    
    
                "target": "nsis",
                "arch": [
                   "x64" //打包64位包
                ]
            }
          ]
    },
    "nsis":{
    
    //打包成安装包的配置
        "oneClick":false,//设置不允许一键安装
        "allowToChangeInstallationDirectory":true //允许安装时选择安装目录
    }
  }

insert image description here
Add electron-builder packaging script in package.json

"pack": "electron-builder --dir",
"build-electron": "electron-builder  "

insert image description here

Vue project compilation

Write the compilation configuration in vue.config.js, and the file will be automatically read when the vue script is compiled

module.exports = {
    
    
  publicPath: process.env.NODE_ENV === 'production'? './': '/',//编译出来的文件使用相对路径可直接浏览器打开渲染,否则需要放在一个http服务器中解析
  outputDir:"dist",//打包输出目录
  assetsDir:"static",//静态资源存放目录

}

Execute the vue compilation script

npm run build

insert image description here

insert image description here

Modify the path of the window rendering webpage in the electron entry file

Because after being packaged into a desktop executable program, the page is no longer rendered from the network address, but the local html+css+JavaScript resources are rendered

 win.loadFile(path.join(__dirname,"../",publicPath,outputDir,"index.html"));//Y因为main.js在electron文件夹中,所以需要../退出一级到根目录下再拼接路径

Set to cancel the default menu directory

const {
    
     app, BrowserWindow,Menu } = require('electron');
//取消窗口顶部菜单目录
Menu.setApplicationMenu(null);

insert image description here

Electron packaging

Execute electron packaging script

npm run build-electron

insert image description here

install app

insert image description here
Select the installation directory
insert image description here

execute program

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44341110/article/details/131721135