简单的搭建一个electron并实现自动更新

本文简单的搭建electron使用electron-builder打包和electron-updater,不对的地方请指出问题,谢谢!

本文不使用Vue  一样可作为参考

electron文档:https://www.electronjs.org/docs

一、搭建electron项目
1、创建一个文件夹并进入文件夹或使用命令创建文件夹 mkdir my-first-electron && cd my-first-electron....创建完成初始化 npm 包

mkdir my-first-electron && cd my-first-electron
npm init

2、初始化完成后安装electron、electron-builder和electron-updater

npm install --save-dev electron
npm i electron-updater
npm i electron-builder

3、创建main.js以及index.html

二、模拟资源服务器文件夹用于更新访问

1、创建一个文件夹并进入文件夹或使用命令创建文件夹.....创建完成后安装http-server

mkdir electron-service && cd electron-service
npm i http-server

2、启动http-server

http-server

启动后会生成ip地址,将ip地址记录下来。不要关闭cmd!!!

三、配置builder以及update操作

1、配置package.json.......重点是 build!!!build!!!其他根据实际情况自行配置

{
  "name": "electronDemo",
  "version": "0.0.1",
  "description": "electronDemo",
  "main": "./main.js",
  "scripts": {
    "start": "electron .",
    "build": "electron-builder"
  },
  "build": {
    "productName": "electronDemo",
    "appId": "electronDemo",
    "directories": {
      "output": "build"
    },
    "publish": [
      {
        "provider": "generic",
        "url": "http://上面记录的ip:8080/"
      }
    ],
    "nsis": {//安装包过程简单的配置有需要可自行修改
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "createDesktopShortcut": true,
      "createStartMenuShortcut": true,
      "perMachine": true,
      "unicode": true
    },
    "win": {
      "icon": "build/icons/icon.ico",
      "target": [
        "nsis",
        "zip"
      ]
    }
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron-builder": "^22.11.7",
    "electron": "^13.1.9"
  },
  "dependencies": {
    "electron-updater": "^4.3.9",
    "update-electron-app": "^2.0.1"
  }
}

2、创建main.js

const { app, BrowserWindow, ipcMain } = require('electron')
const { autoUpdater } = require('electron-updater')
const uploadUrl = "http://记录的ip:8080/" 

const path = require('path')

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration:true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })
    
  updateHandle();

  mainWindow.loadFile('index.html')
}

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()
})

function updateHandle() {
  const os = require('os');
 
  autoUpdater.setFeedURL(uploadUrl);
  autoUpdater.on('error', function (error) {
    sendUpdateMessage('检查更新出错')
  });
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage('正在检查更新')
  });
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage('正在下载新版本')
  });
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage("当前为最新版本")
  });
 
  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    mainWindow.webContents.send('downloadProgress', progressObj)
  })

  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, 
  releaseDate, updateUrl, quitAndUpdate) {
    console.log('更新完成')
    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log("开始更新");
      autoUpdater.quitAndInstall();
    });

    mainWindow.webContents.send('isUpdateNow')
  });

  //通讯渲染层
  ipcMain.on("checkForUpdate",()=>{
      autoUpdater.checkForUpdates();
  })
}
 
// 通过main进程发送事件给renderer进程,提示更新信息
function sendUpdateMessage(text) {
  mainWindow.webContents.send('message', text)
}

2.1、创建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、创建index.html

<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello Electron!</title>
  </head>
  <body>
    <h1>Hello Electron!</h1>
    <button onclick="checkUpdate()">更新</button>
    <script>
      const { ipcRenderer } = require('electron');

      //主线程使用mainWindow.webContents.send传输,渲染线程使用ipcRenderer接收
      //渲染线程使用ipcRenderer.send传输,主线程使用ipcMain接收

      //接收主线程信息 
      ipcRenderer.on("message", (event, text) => {
        this.tips = text;
      });

      ipcRenderer.on("downloadProgress", (event, progressObj)=> {
        this.downloadPercent = progressObj.percent || 0;
      });

      ipcRenderer.on("isUpdateNow", () => {
        ipcRenderer.send("isUpdateNow");
      });

        //主动触发主线程checkForUpdate。。。有需要可改为自动触发
      function checkUpdate () {
        ipcRenderer.send("checkForUpdate");
      }
    </script>
  </body>
</html>

测试是否能正常显示渲染页面npm start!!!!

四、测试并配置更新

1、打开package.json 查看当前设置version版本   例:"version":"0.0.1"

确认好版本号后运行打包命令

npm run build

打包好后会发现根目录会多出一个build文件

进入build文件夹中找到 *** Setup 0.0.1.exe 类似的安装包进行安装

2、打开package.json文件  修改版本号改为  "version":"0.0.2"

确认版本号和之前安装的版本号不一致!!!!!!

确认好后运行打包命令

重点!!!!!!!!!!!!!!!!!!!

进入build文件夹中 找到*** Setup 0.0.2.exe 类似的安装包 和 latest.yml文件!!!!!

将这两个复制到之前创建的http-server服务的文件夹中 。。。。根据本文索引因名为electron-service的文件夹中

http-server一定要启动!!!!!!!!!!!!!!!!!!!!!!!!

现在打开之前安装的应用程序,点击更新就可以在控制台上看到操作了

控制台在窗体 view/toggle Developer Tools中

解决问题

1、安装打包过程中出现出现node.js install什么的报错,需要添加镜像

(1)、C:\Users\用户名\    下创建.npmrc文件添加淘宝镜像

registry = https://registry.npm.taobao.org/
ELECTRON_MIRROR = https://npm.taobao.org/mirrors/electron/
ELECTRON_BUILDER_BINARIES_MIRROR = http://npm.taobao.org/mirrors/electron-builder-binaries/

(2)、使用命令添加淘宝镜像

npm config set registry https://registry.npm.taobao.org/
npm config set ELECTRON_MIRROR https://npm.taobao.org/mirrors/electron/
npm config set ELECTRON_BUILDER_BINARIES_MIRROR http://npm.taobao.org/mirrors/electron-builder-binaries/

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue Electron 是一种用于构建跨平台桌面应用程序的开源框架,结合了 Vue.js 和 Electron.js 技术。在 Vue Electron实现自动更新需要借助 Electron 的 autoUpdater 模块和一些其他辅助工具。 首先,需要在主进程(`main.js`)中配置自动更新。可以使用 Electron 的 autoUpdater 模块来检查新版本,并自动下载和安装更新。具体步骤如下: 1. 导入 autoUpdater 模块:在 `main.js` 文件中添加 `const { autoUpdater } = require('electron-updater')`。 2. 配置更新服务器地址:通过 `autoUpdater.setFeedURL()` 方法设置更新服务器的地址,例如 `autoUpdater.setFeedURL('https://your-update-server-url')`。 3. 监听更新事件:使用 `autoUpdater.on()` 方法监听自动更新过程中的各个事件。例如可以监听 `checking-for-update`、`update-available`、`update-not-available`、`download-progress` 和 `update-downloaded`。 4. 触发检查更新:通过 `autoUpdater.checkForUpdates()` 方法触发检查更新的过程,在应用启动时或者可以通过某个按钮点击事件来手动检查更新。 接下来,需要在渲染进程(Vue 组件)中显示更新提示和进行更新操作。具体步骤如下: 1. 在渲染进程的代码中,可以监听 `message` 事件来接收主进程发送的消息,从而在用户界面上显示更新提示。 2. 监听到更新提示后,可以弹出一个对话框,询问用户是否进行更新。如果用户选择更新,可以通过 `ipcRenderer.send()` 方法向主进程发送消息,触发下载和安装更新的过程。 3. 主进程监听到渲染进程发送的更新请求后,可以通过 `autoUpdater.downloadUpdate()` 方法来下载更新文件。 4. 下载完成后,通过 `autoUpdater.quitAndInstall()` 方法来安装更新并重启应用。 以上就是使用 Vue Electron 实现自动更新的基本步骤。需要注意的是,还需要在应用的打包配置中加入相应的逻辑,以使自动更新在不同平台下运行正常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值