vue3+vite+electron开发桌面端应用流程

一、创建项目

  1. 初始化项目: npm init vite@latest'
    project name: 输入项目名称,select a framework: 选择框架vue
    select a variant:选择使用js或者ts
  2. 安装默认依赖包: 进入项目,npm install
  3. 安装electron: npm install --save-dev electron
  4. 安装热加载(自动加载更新): npm install electron-reload --save-dev(注意:electron-reload目前最新版本是2.0.0-alpha.1, 需要安装指定的稳定版)
  5. 安装打包工具: npm install electron-builder --dev

二、配置electron相关的文件

  1. 在根目标下创建文件夹electron,存放electron相关的文件

  2. electron 文件夹下创建preload.js文件, 通过预加载脚本从渲染器访问Node.js。

    // preload.js
    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. electron 文件夹下创建main.js, 作为electron的入口文件

    // main.js
    // 控制应用生命周期和创建原生浏览器窗口的模组
    // app 模块,它控制应用程序的事件生命周期。
    // BrowserWindow 模块,它创建和管理应用程序窗口。
    const { app, BrowserWindow } = require('electron');
    const path = require('path')
    // 打开窗口
    function createWindow () {
    const mainWindow = new BrowserWindow({
    width: 800, // 窗口的宽度
    height: 600, // 窗口的高度
    // 网页功能设置
    webPreferences: {
    nodeIntegration: true, // 是否启用Node integration. 默认值为 false.
    contextIsolation: false, // 是否在独立 JavaScript 环境中运行 electron API和指定的preload 脚本. 默认为 true
    enableRemoteModule: true, // 启用或远程模块, 默认为 true
    preload: path.join(__dirname, 'preload.js'), // 使用预加载脚
    },
    autoHideMenuBar: true, // 窗口菜单栏是否自动隐藏,默认false
    })
    // 通过改变变量值来控制加载的文件,dev 或者build时修改env值。
    let env = 'pro';
    // 配置热更新
    if (env == 'pro') {
    const elePath = path.join(__dirname, '../node_modules/electron')
    require('electron-reload')('./', {
    electron: require(elePath),
    })
    // 热更新监听窗口,这里是vue启动时的地址
    mainWindow.loadURL('http://localhost:8888')
    // 打开开发工具
    mainWindow.webContents.openDevTools()
    } else {
    // 生产环境中要加载文件 index.html
    mainWindow.loadFile(path.resolve(__dirname, '../dist/index.html'))
    }
    }

    // 这段程序将会在 electron 结束初始化和创建浏览器窗口的时候调用
    app.whenReady().then(() => {
    createWindow()
    app.on('activate', function () {
    // 如果没有其他打开的窗口,那么程序会重新创建一个窗口。
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
    })

    // 当所有窗口都被关闭的时候退出程序。
    app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
    })

  4. 根目录下创建electron-builder.json

    // electron-builder.json
    {
    "productName": "appName", // 包名称
    "files": ["./electron/main.js", "./dist"],
    "extraFiles": ["./videos", "./cvideo"],
    "directories": {
    "output": "./builder"
    }
    }

  5. package.json中配置electron命令
    在scripts中添加electron运行和打包命令:

     "electron:serve": "electron .", 
     "electron:build": "vite build & electron-builder build --config electron-builder.json"
    

三、项目启动和打包

  1. 启动vue项目: npm run dev
  2. 启动electron: npm run electron:serve
  3. 打包electron: npm run electron:build

四、常见问题及解决方法

  1. 报错信息:electron Unable to find Electron app at *****
    报错原因:入口文件路径错误
    解决方法:在package中添加electron应用程序的入口文件路径:"main": "electron/main.js"

  2. 报错信息:ReferenceError: require is not defined in ES module scope, you can use import instead
    This file is being treated as an ES module because it has a '.js' file extension an ***
    报错原因:require 在 ESM 规范中未定义
    解决方法:删除"type": "module"

  3. build时报错信息:https://github.com/electron/electron/releases/download/v20.3.1/electron-v20.3.1-win32-x64.zip": dial tcp 20.205.243.166:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    报错原因:打包时要到github上下载electron, 速度很慢导致失败。
    解决方法:从github上下载electron到C:\Users\xxx\AppData\Local\electron\Cache\xxxxx

  4. 打包后的exe文件执行时页面空白
    报错原因:资源路径是被打包成了绝对路径
    解决方法:找到vite.config.js进行修改文件加载路径:

    export default defineConfig({
    base: './',设置基础路径为根目录
    });

相关推荐
IT 古月方源4 分钟前
GRE技术的详细解释
运维·前端·网络·tcp/ip·华为·智能路由器
myepicure8887 分钟前
Windows下调试Dify相关组件(1)--前端Web
前端·llm
JosieBook20 分钟前
【ASP.NET学习】Web Pages 最简单的网页编程开发模型
前端·asp.net·菜鸟教程
雨 子1 小时前
Spring Web MVC
前端·spring boot·spring·mvc·postman
计算机毕设指导61 小时前
基于Springboot美食推荐商城系统【附源码】
java·前端·spring boot·后端·spring·tomcat·美食
!win !1 小时前
外部H5唤起常用小程序链接规则整理
前端·小程序
染指悲剧1 小时前
vue实现虚拟列表滚动
前端·javascript·vue.js
林涧泣2 小时前
【Uniapp-Vue3】navigator路由与页面跳转
前端·vue.js·uni-app
浩浩测试一下3 小时前
Web渗透测试之XSS跨站脚本之JS输出 以及 什么是闭合标签 一篇文章给你说明白
前端·javascript·安全·web安全·网络安全·html·系统安全
一棵开花的树,枝芽无限靠近你3 小时前
【PPTist】插入形状、插入图片、插入图表
前端·笔记·学习·编辑器·ppt·pptist