图文摘要

vue3项目集成electron

vue3项目集成electron

作者: 来源: 发布时间:2023-12-08 10:05:28

git clone https://github.com/electron/electron-quick-start

下载以后主要是要用到代码里的main.js和preload.js两个文件。如果不下载,直接复制下面的两个文件代码即可。

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// 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.
app.whenReady().then(() => {
  createWindow()

  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 (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// 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.


preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
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])
  }
})


安装依赖

electron不多说。concurrently和 wait-on解释一下。
开发环境的运行条件是,先运行vite启动服务,然后electron去加载本地服务url。这里需要安装两个依赖。

concurrently:阻塞运行多个命令,-k参数用来清除其它已经存在或者挂掉的进程

-wait-on:等待资源,此处用来等待url可访问

npm install electron --save-dev
npm install concurrently wait-on --save-dev


electron/main.js

根据需求,我添加了Menu.setApplicationMenu(null)隐藏菜单栏,frame是否展示顶部导航的配置,默认为true。mainWindow.loadFile(‘index.html’)修改成了mainWindow.loadURL(关键),具体配置如下。

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')

//这里的配置手动写的,也可以使用cross-env插件配置
const mode = 'development'

/*隐藏electron创听的菜单栏*/
Menu.setApplicationMenu(null)

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        frame: true /*是否展示顶部导航  去掉关闭按钮  最大化最小化按钮*/ ,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
    })

    // and load the index.html of the app.
    // mainWindow.loadFile('index.html')  修改成如下

    mainWindow.loadURL(mode === 'development' ? 'http://localhost:2103' : `file://${path.join(__dirname, '../dist/index.html')}`)

    // Open the DevTools.
    if (mode === 'development') {
        mainWindow.webContents.openDevTools()
    }
}

// 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.
app.whenReady().then(() => {
    createWindow()

    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 (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function() {
    if (process.platform !== 'darwin') app.quit()
})

// 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.


3.vite.config.js

配置base: ‘./’

4.package.json

main:main.js修改成main:electron/main.js。添加electron和electron:serve指令

    "main": "electron/main.js",
    "scripts": {
        "dev": "vite --host",
        "serve": "vite preview",
        "build": "vite build",
        "electron": "wait-on tcp:2103 && electron . --mode=development ",
        "electron:serve": "concurrently -k \"npm run dev\" \"npm run electron\""
    },

运行项目

npm run electron:serve

1.如果运行不成功或者成功之后白屏,可查看以下几个关键配置

端口一致

electron热更新

electron可以使用electron-reloader这个依赖实现项目热更新:更改html/js/css代码框架自动更新,大大提高开发效率,不用每次都npm start重新启动。

1.安装electron-reloader依赖

npm install --save-dev electron-reloader

2.程序入口文件(一般是index.js)中加入以下代码

// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu } = require('electron')
const path = require('path')

//这里的配置手动写的,也可以使用cross-env插件配置
const mode = 'development'

/*隐藏electron创听的菜单栏*/
// Menu.setApplicationMenu(null)


//热加载 以下为增加部分
try {
  require('electron-reloader')(module,{});
} catch (_) {}


function createWindow() {

重启一下项目就可以了。

3、打包生成桌面应用

1.安装打包插件 electron-builder

npm install electron-builder --save-dev

2.package.json添加electron:build命令,和build配置

    "main": "electron/main.js",
    "scripts": {
        "dev": "vite --host",
        "serve": "vite preview",
        "build": "vite build",
        "electron": "wait-on tcp:2103 && electron . --mode=development ",
        "electron:serve": "concurrently -k \"npm run dev\" \"npm run electron\"",
        "electron:build": "npm run build && electron-builder"
    },
     "build": {
        "appId": "8a06282fb08c48eeacb15bfbe4d3a35b",
        "productName": "ElectronApp",
        "copyright": "Copyright © 2022 <项目名称>",
        "mac": {
            "category": "public.app-category.utilities"
        },
        "nsis": {
            "oneClick": false,
            "allowToChangeInstallationDirectory": true
        },
        "files": [
            "dist/**/*",
            "electron/**/*"
        ],
        "directories": {
            "buildResources": "assets",
            "output": "dist_electron"
        }
    }

注意electron/main.js里的配置

const mode = 'production'


打包相关报错问题:

electron-v27.1.3-win32-x64.zip和SHASUM验证文件

下载两个文件。将zip文件和解压后的文件夹以及SHASUM验证文件放到 C:\Users\Administrator\AppData\Local\electron\Cache 目录下


winCodeSign-2.6.0.7z解压到C:\Users\yaozh\AppData\Local\electron-builder\Cache\winCodeSign目录下

(最终路径为C:\Users\yaozh\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.6.0)


nsis-3.0.4.1.7z和nsis-resources-3.4.1.7z解压到

C:\Users\yaozh\AppData\Local\electron-builder\Cache\nsis\