前端使用electron+vue3+ts搭建一个桌面端应用且可以热更新

技术

字体加黑的是必要的技术,其他的库是可以自由选择的

  • electron 13.0.0
  • vue3 + ts
  • electron-updater
  • node 16.13.1
  • element-plus
  • less
  • meansjs

搭建vue3项目

安装vue-cli

如果有没有安装的话就全局安装


npm install -g @vue/cli

复制代码

创建vue3项目

跟vue2创建项目差不多,需要配置什么自己去选择,这儿我选择的是ts开发


vue create electron-vue3

复制代码

启动项目:


yarn serve

复制代码

启动成功以后,开始安装electron;

安装Electron

electron-builder官方文档

在此安装的时候会叫你选择版本,你根据自己的要求选择就可(我的是13.0.0)

安装依赖:

vue add electron-builder
复制代码

启动项目:


yarn electron:serve

复制代码

我们在启动的时候会报错如下图:

1.png

2.png

解决方案:

安装:

yarn add ts-loader@8.2.0
复制代码

找到background.ts文件,将e修改


try {
  await installExtension(VUEJS3_DEVTOOLS)
} catch (e:any) {
  console.error('Vue Devtools failed to install:', e.toString())
}

复制代码

然后再次启动即可,在启动的过程中有点慢,需要耐心等待;后续我会说怎么解决

background.ts文件修改

创建主进程文件

在src随意位置创建一个host文件,可以在common文件中随意封装很多文件然后再host/index.ts文件中引入使用即可

// src/host/index.ts

import { ipcMain} from 'electron';
export default (win:any)=>{
    // 窗口最小化
    ipcMain.on("window-minimize", function () {
      // 收到渲染进程的窗口最小化操作的通知,并调用窗口最小化函数,执行该操作
      win.minimize();
    });
  
    // 窗口最大化
    ipcMain.on("window-maximize", function () {
      if (win.isMaximized()) {
        win.restore();
      } else {
        win.maximize();
      }
    });
  
    // 关闭窗口
    ipcMain.on("window-close", function () {
      win.hide();
      win.close();
    });
}
复制代码

修改background.ts

由于太多了,不好描述我就直接贴上代码了,代码中有注释大家也可以查看;还有就是我们在上面说到的,项目启动很慢的问题,在这而也是得到了解决的;

大致讲解

  • hout/index文件是一个主进程接收发送文件
  • await installExtension(VUEJS3_DEVTOOLS)替换成session.defaultSession.loadExtension( path.resolve(__dirname, "../devTools/chrome"));会提高启动速度,至于为什么请自行百度
  • 其他的new BrowserWindow参数做了一些调整,就没怎么修改了;好理解
'use strict'

import { app, protocol, BrowserWindow,session } from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
// import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'; // 会导致启动的时候很慢,所以不用
const isDevelopment = process.env.NODE_ENV !== 'production';
const path = require("path");
import host from '@/host/index';

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
]);

let win:any;

async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1000,
    height: 600,
    minWidth: 800,
    minHeight: 600,
    // 不要边框
    frame: true,
    webPreferences: {
      webviewTag: true,
      // 禁止同源策略,避免 axios 无法使用
      webSecurity: false,
      // Required for Spectron testing
      enableRemoteModule: !!process.env.IS_TEST,
      nodeIntegration: true,
      contextIsolation: false
    }
  })


  // 主进程
  host(win);

  // 开发环境
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string)
    if (!process.env.IS_TEST) win.webContents.openDevTools() // 打开控制台
  } else {
    // 生产环境
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}

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

app.on('activate', () => {
  // 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()
})


// 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.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      // await installExtension(VUEJS3_DEVTOOLS) // 会导致启动的时候很慢
      session.defaultSession.loadExtension( path.resolve(__dirname, "../devTools/chrome"));
    } catch (e:any) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow();
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}


复制代码

当你做到这儿的时候,你的启动速度会贼快

然后我们开始配置vue.config.js;打包的時候需要的

vue.config.js

这里的配置文件我是根据初始化项目来进行配置的,如果你的项目没有去修改初始文件的名称的话;可将以下代码复制进去即可。代码中我都写了注释的,大家需要修改什么地方自己更改就好

注意的地方(重点):

  • appId
  • icon
  • guid
  • include

1、appId/guid需保持一致; 2、include重点中的重点,如果你需要热更新的话;这个文件一定要配置,不然你在卸载/更新后安装软件安装不上;主要原因注册机的问题。这个文件最有一句代码也是要和appId一致的;

const { defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, // 引入插件不使用时不报报错
  configureWebpack: {
    externals: {
      'electron': 'require("electron")'
    },
  },

  // 第三方插件配置
  pluginOptions: {
    // vue-cli-plugin-electron-builder 配置
    electronBuilder: {
      nodeIntegration: true,
      // 设置应用主进程的入口
      mainProcessFile: "src/background.ts",
      // 设置应用渲染进程的入口
      rendererProcessFile: "src/main.ts",
      customFileProtocol: "../",
      // 打包选项
      builderOptions: {
        // 解决的问题:在安装到电脑后,系统通知无法工作
        appId: "com.zhuhong.vue3", // 软件id
        productName: "JSON工具", // 打包后的名称
        // windows系统相关配置
        win: {
          // 应用图标路径(Windows 系统中 icon 需要 256 * 256 的 ico 格式图片)
          icon: "./src/assets/login-icon.png",
          target: {
            target: "nsis",
            // 支持 64 位的 Windows 系统
            arch: ["x64"],
          },
        },
        nsis: {
          // 如果为false,想要给电脑所有用户安装必须使用管理员权限
          allowElevation: true,
          // 是否一键安装
          oneClick: false,
          // 允许修改安装目录
          allowToChangeInstallationDirectory: true,
          "guid": "com.zhuhong.vue3", // 软件id
          "include": "./installer.nsh"
        },
      },
    },
  },
})

复制代码

根目录创建installer.nsh文件

!macro customInit

DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\com.zhuhong.vue3"

!macroend

复制代码

打包:

yarn electron:build

复制代码

如果配置到这儿打包没得问题,那么你的项目基本上就行了;

Snipaste_2023-01-13_15-41-58.png

最后呢?就是热更新了;需要的可以继续往下看

热更新

安装

yarn add electron-updater
复制代码

新建JSPatch文件

注意:

  • autoUpdater.setFeedURL一定要写在外面,不然打包的时候会报错
  • url: process.env.VUE_APP_HOT_UPDATE, 不能这样使用;否则打包也会报错
  • url链接地址事你存放打包文件的地址
  • 需要将此文件引入background.ts文件中
  • 必须在app.on('ready', 函数中引用
// src/host/common/JSPatch.ts
import { ipcMain } from "electron";
const { autoUpdater } = require("electron-updater");

autoUpdater.autoDownload = false; // 是否自动更新
autoUpdater.autoInstallOnAppQuit = true // APP退出的时候自动安装

/*
  * 在开启更新监听事件之前设置
  * 一定要保证该地址下面包含lasted.yml文件和需要更新的exe文件
  */
autoUpdater.setFeedURL({
  provider: 'generic',
  url: 'https://', // 打包文件存放地址
});

export default (win:any)=>{
  
  // 发送消息给渲染线程
  function sendStatusToWindow(status?:any, params?:any) {
    win.webContents.send(status, params);
  }
  
  autoUpdater.on('checking-for-update', () => {
    sendStatusToWindow('Checking for update...');
  })
  autoUpdater.on('update-available', (info:any) => {
    // 可以更新版本
    sendStatusToWindow('autoUpdater-canUpdate', info)
  })
  
  autoUpdater.on('error', (err:any) => {
    // 更新错误
    sendStatusToWindow('autoUpdater-error', err)
  })
  // 发起更新程序
  ipcMain.on('autoUpdater-toDownload', () => {
    autoUpdater.downloadUpdate()
  })
  autoUpdater.on('download-progress', (progressObj:any) => {
    // 正在下载的下载进度
    sendStatusToWindow('autoUpdater-progress', progressObj)
  })
  autoUpdater.on('update-downloaded', () => {
    // 下载完成
    sendStatusToWindow('autoUpdater-downloaded')
  })
  
  // 退出程序
  ipcMain.on('exit-app', () => {
    autoUpdater.quitAndInstall()
  })
  
  // 重新检查是否有新版本更新
  ipcMain.on('monitor-update-system',()=>{
    autoUpdater.checkForUpdates()
  })

  // 检测是否有更新
  setTimeout(() => {
    autoUpdater.checkForUpdates();
  }, 5000);

}
复制代码

新建一个组件或者在app.vue中使用也可以jspatch

<template>
    <div class="jspatch">
      <el-dialog
        title="JSON工具更新中......"
        v-model="showUpdater"
        :close-on-click-modal="false"
        :close-on-press-escape="true"
        :show-close="false"
        width="40%"
        top="26vh"
        center
      >
        <template v-if="downloadProcess">
          <p> {{`当前:【${downloadProcess.transferred}】 / 共【${downloadProcess.total}】`}}</p>
          <el-progress
            :text-inside="true"
            :stroke-width="18"
            status="warning"
            :percentage="downloadProcess.percent"
          ></el-progress>
          <p>正在下载({{ downloadProcess.speed }})......</p>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang='ts'>
  import { defineComponent, reactive, toRefs } from "vue";
  import { ipcRenderer } from "electron";
  import { ElMessage ,ElMessageBox } from 'element-plus';
  
  export default defineComponent({
    name: "Jspatch",
    setup(props: any, { emit }: { emit: any }) {
      const data = reactive({
        showUpdater: false,
        downloadProcess: {
          percent: 10,
          speed: 0,
          transferred:'1kb',
          total:"2M"
        },
      });
      // 发现新版本 once
      ipcRenderer.on("autoUpdater-canUpdate", (event, info) => {
        /*
         * 这儿会监听,如果info.version比现在版本小;就会触发;反之,不会触发
         */
        ElMessageBox.confirm(`发现有新版本【v${info.version}】,是否更新?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "warning",
        }).then(() => {
          ipcRenderer.send("autoUpdater-toDownload");
        });
      });
      // 下载进度
      ipcRenderer.on("autoUpdater-progress", (event, process) => {
        if (process.transferred >= 1024 * 1024) {
          process.transferred =
            (process.transferred / 1024 / 1024).toFixed(2) + "M";
        } else {
          process.transferred = (process.transferred / 1024).toFixed(2) + "K";
        }
        if (process.total >= 1024 * 1024) {
          process.total = (process.total / 1024 / 1024).toFixed(2) + "M";
        } else {
          process.total = (process.total / 1024).toFixed(2) + "K";
        }
        if (process.bytesPerSecond >= 1024 * 1024) {
          process.speed =
            (process.bytesPerSecond / 1024 / 1024).toFixed(2) + "M/s";
        } else if (process.bytesPerSecond >= 1024) {
          process.speed = (process.bytesPerSecond / 1024).toFixed(2) + "K/s";
        } else {
          process.speed = process.bytesPerSecond + "B/s";
        }
        process.percent = process.percent.toFixed(2);
        data.downloadProcess = process;
        data.showUpdater = true;
      });
      // 下载更新失败
      ipcRenderer.once("autoUpdater-error", () => {
        ElMessage.error("更新失败!");
        data.showUpdater = false;
      });
      // 下载完成
      ipcRenderer.once("autoUpdater-downloaded", () => {
        data.showUpdater = false;
        ElMessageBox.confirm(`更新完成,是否关闭应用程序安装新版本?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "warning",
        }).then(() => {
          ipcRenderer.send("exit-app");
        });
      });
      return {
        ...toRefs(data),
      };
    },
  });
  </script>
  
  <style scoped lang='less'>
  .jspatch {
    /deep/ .el-dialog__header {
      font-weight: 700;
  
      .el-dialog__title {
        color: #00adb5;
      }
    }
  }
  </style>
复制代码

最后修改一哈vue.config.js就完成了

将以下代码复制到vue.config.js的builderOptions对象中即可

publish: [
    {
        provider: "generic",
        url: 'https:', // 打包文件地址,与以上链接需相同
    },
],
复制代码

然后再次打包安装测试;没有问题就可以上线了

也可以查看线上代码

json-tool工具GitHub仓库

json-tool工具软件

以前的文章

今天的分享就到这儿了,期待这个文章对你有帮助!

猜你喜欢

转载自juejin.im/post/7188041961599664165