使用Electron + Vue3 + TS搭建桌面端应用并可热更新

以下是必要的技术:

  • Electron 13.0.0
  • Vue3 + TS
  • Electron-updater
  • Node 16.13.1
  • Element-plus
  • Less
  • Meansjs

搭建Vue3项目

  1. 安装Vue-cli(如果未安装): npm install -g @vue/cli
  2. 创建Vue3项目:vue create electron-vue3
  3. 启动项目:yarn serve

安装Electron

  1. 安装Electron:vue add electron-builder
  2. 启动项目:yarn electron:serve
  3. 如果报错,需要安装ts-loader: yarn add [email protected]
  4. 修改background.ts文件中的代码(将await installExtension(VUEJS3_DEVTOOLS)改为session.defaultSession.loadExtension( path.resolve(__dirname, "../devTools/chrome")))。

创建主进程文件

  1. 在src文件夹中创建host文件,并在其中添加index.ts文件。
  2. 在index.ts文件中添加代码(窗口最小化、最大化、关闭操作)。
  3. 修改background.ts文件并导入host文件。
  4. 遇到启动速度很慢的问题,可以将background.ts文件中的await installExtension(VUEJS3_DEVTOOLS)替换为session.defaultSession.loadExtension( path.resolve(__dirname, "../devTools/chrome")),并对new BrowserWindow参数进行一些调整。

配置vue.config.js文件

  1. 复制以下代码,并根据需要修改appId、icon、guid、include等参数。
const {
    
     defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
    
    
  transpileDependencies: true,
  lintOnSave: false,
  configureWebpack: {
    
    
    externals: {
    
    
      'electron': 'require("electron")'
    },
  },
  pluginOptions: {
    
    
    electronBuilder: {
    
    
      nodeIntegration: true,
      mainProcessFile: "src/background.ts",
      rendererProcessFile: "src/main.ts",
      customFileProtocol: "../",
      builderOptions: {
    
    
        appId: "com.zhuhong.vue3",
        productName: "JSON工具",
        win: {
    
    
          icon: "./src/assets/login-icon.png",
          target: {
    
    
            target: "nsis",
            arch: ["x64"],
          },
        },
        nsis: {
    
    
          allowElevation: true,
          oneClick: false,
          allowToChangeInstallationDirectory: true,
          "guid": "com.zhuhong.vue3",
          "include": "./installer.nsh"
        },
      },
    },
  },
})

  1. 创建installer.nsh文件,并将以下代码复制进去:
!macro customInit
DeleteRegKey HKLM "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\com.zhuhong.vue3"
!macroend

  1. 打包:yarn electron:build

热更新

  1. 安装electron-updater:yarn add electron-updater
  2. 创建JSPatch文件,并将以下代码复制进去:
import {
    
     ipcMain } from "electron";
const {
    
     autoUpdater } = require("electron-updater");

autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = true;

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',

以上为详细的搭建步骤和必要的技术。

猜你喜欢

转载自blog.csdn.net/qq_27244301/article/details/130366014