vue3集成electron

当前文章基于创建一个vue3应用

1、安装electron开发依赖

最新版本:npm install --save-dev electron

指定版本:npm install --save-dev electron@22.2.0

2、添加主进程文件main.js、预加载脚本preload.js

  • __dirname 字符串指向当前正在执行脚本的路径 (在本例中,它指向你的项目的根文件夹)。
  • path.join API 将多个路径联结在一起,创建一个跨平台的路径字符串。

项目根目录新建文件electron/main.js:

const { app, protocol, BrowserWindow, globalShortcut } = require('electron')
// 需在当前文件内开头引入 Node.js 的 'path' 模块
const path = require('path')

app.commandLine.appendSwitch("--ignore-certificate-errors", "true");
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    { scheme: "app", privileges: { secure: true, standard: true } }
]);

const createWindow = () => {
    const win = new BrowserWindow({
        minWidth: 960,
        minHeight: 540,
        width: 960,
        height: 540,
        //窗口是否在屏幕居中. 默认值为 false
        center: true,
        //设置为 false 时可以创建一个无边框窗口 默认值为 true。
        frame: false,
        //窗口是否在创建时显示。 默认值为 true。
        show: true,
        webPreferences: {
            nodeIntegration: true,
            nodeIntegrationInWorker: true,
            preload: path.join(__dirname, 'preload.js'),
            webSecurity: false,
        }
    })
    win.setMenu(null)
    if (app.isPackaged) {
        win.loadURL(`file://${path.join(__dirname, '../dist/index.html')}`)
    } else {
        win.loadURL('http://127.0.0.1:5173/')
           //win.loadURL('http://localhost:5173/')
        win.webContents.openDevTools()
    }
    globalShortcut.register("CommandOrControl+Shift+i", function () {
        win.webContents.openDevTools();
    });

}

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

    createWindow()

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

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

 项目根目录新建文件electron/preload.js:(示例)

// 所有的 Node.js API接口 都可以在 preload 进程中被调用.
// 它拥有与Chrome扩展一样的沙盒。
window.addEventListener('DOMContentLoaded', () => {
    const replaceText = (selector, text) => {
      const element = document.getElementById(selector)
      if (element) element.innerText = text
    }
  
    for (const dependency of ['chrome', 'node', 'electron']) {
      replaceText(`${dependency}-version`, process.versions[dependency])
    }
  })

3、在package.json指定electron主进程文件路径,在scripts字段下增加一条start命令

 添加:

"main": "electron/main.js"

"scripts": {

"start": "vite | electron ."

}

package.json:

{
  "name": "job-hopping",
  "version": "0.0.0",
  "private": true,
  "main": "electron/main.js",//指定electron主进程文件路径
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "vite | electron ."
  },
  "dependencies": {
    "vue": "^3.3.2"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.2.3",
    "electron": "^22.2.0",
    "electron-builder": "^23.6.0",
    "vite": "^4.3.5"
  }
}

4、启动electron(开发调试时)

npm start

若出现下图的情况,可能是vite启动后的地址不是127.0.0.1,而是localhost

这时可以将主进程文件main.js第34行 win.loadURL('http://127.0.0.1:5173/')修改为win.loadURL('http://localhost:5173/')

 修改后,成功显示

 5、electron打包

5.1、安装electron打包开发依赖

最新版本:npm install --save-dev electron-builder

指定版本:npm install --save-dev electron-builder@23.6.0

5.2、引入相关图标文件

在项目根目录下新建build\electron-icon文件夹,然后分别将.icns、.ico、.png类型文件放置此文件夹下

注意:windows系统中icon需要256*256的ico格式图片

5.3、在package.json添加author、description、build字段,同时在scripts字段添加electron:build命令

package.json:

{
  "name": "job-hopping",
  "version": "0.0.0",
  "private": true,
  "author": {
    "name": "lsl",
    "email": "lsl@lsl.com.cn"
  },
  "description": "lsl",
  "main": "electron/main.js",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "vite | electron .",
    "electron:build": "vite build && electron-builder"
  },
  "dependencies": {
    "vue": "^3.3.2"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.2.3",
    "electron": "^22.2.0",
    "electron-builder": "^23.6.0",
    "vite": "^4.3.5"
  },
  "build": {
    "appId": "lsl.first.app",
    "productName": "ElectronApp",
    "copyright": "Copyright © 2023 lsl",
    "directories": {
      "output": "dist_electron"
    },
    "win": {
      // 图标路径 windows系统中icon需要256*256的ico格式图片,更换应用图标亦在此处
      "icon": "./build/electron-icon/icon.ico",
      "target": [
        {
          "target": "nsis",
          "arch": [
            "x64"
          ]
        }
      ]
    },
    "dmg": {
      "contents": [
        {
          "x": 410,
          "y": 150,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 130,
          "y": 150,
          "type": "file"
        }
      ]
    },
    "linux": {
      "icon": "./build/electron-icon/icon.png",
      "target": "AppImage"
    },
    "mac": {
      "icon": "./build/electron-icon/icon.icns"
    },
    "files": [
      "./dist",
      "./electron",
      "!**/node_modules/**"
    ],
    "asar": false, //打包时不进行加密
    "nsis": {
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "installerIcon": "./build/electron-icon/icon.ico",
      "uninstallerIcon": "./build/electron-icon/icon.ico",
      "installerHeaderIcon": "./build/electron-icon/icon.ico",
      "createDesktopShortcut": true,
      "createStartMenuShortcut": true
    }
  }
}

 5.4、执行打包命令,打包后的文件在当前项目的dist_electron文件夹下

打包命令: npm run electron:build

 输出位置:

5.5、此时安装启动后会发现系统又白屏了,此时需要修改vite.config.js,添加base字段

添加:base: "./"

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

5.5、重新打包安装启动,完成