如果是vue-cli-plugin-electron-builder打包则会报错如下:
Question||'build' in the application package.json is not supported since 3.0
因为3.0后不支持json的方式, 需要移除package.json “build”
'use strict'
import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
import * as path from 'path';
const fs = require('fs');
const { autoUpdater } = require('electron-updater');
const isDevelopment = process.env.NODE_ENV !== 'production';
const DOWNLOAD_URL = 'http://localhost:3006/';
var package_json = require('../package.json');
var mainWindow = null;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
async function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
mainWindow.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(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
console.log('ready')
createWindow()
updateHandle();
})
// 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()
})
}
}
function updateHandle() {
autoUpdater.currentVersion = package_json.version;
autoUpdater.setFeedURL(DOWNLOAD_URL);
// 取消自动更新
autoUpdater.autoDownload = false;
autoUpdater.on('checking-for-update', (info) => {
// 开始检查是否有新版本
// 可以在这里提醒用户正在查找新版本
console.log('checking-for-update')
})
autoUpdater.on('update-available', (info) => {
// 检查到有新版本
// 提醒用户已经找到了新版本
console.log('检查到有新版本')
})
autoUpdater.on('error', (err) => {
// 自动升级遇到错误
})
}
'use strict'
import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const fs = require('fs');
const { autoUpdater } = require('electron-updater');
const isDevelopment = process.env.NODE_ENV !== 'production';
const DOWNLOAD_URL = 'http://localhost:3006/';
var package_json = require('../package.json');
var mainWindow = null;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
async function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
}
})
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
mainWindow.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(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
console.log('ready')
createWindow()
updateHandle();
})
// 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()
})
}
}
const deleteFile = (path) => {
var files = [];
if( fs.existsSync(path) ) {
files = fs.readdirSync(path);
files.forEach(function(file){
var curPath = path + "/" + file;
if(fs.statSync(curPath).isDirectory()) {
deleteFile(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
function updateHandle() {
autoUpdater.currentVersion = package_json.version;
autoUpdater.setFeedURL(DOWNLOAD_URL);
// 取消自动更新
autoUpdater.autoDownload = false;
autoUpdater.on('checking-for-update', (info) => {
// 开始检查是否有新版本
// 可以在这里提醒用户正在查找新版本
})
autoUpdater.on('update-available', (info) => {
// 检查到有新版本
// 提醒用户已经找到了新版本
console.log(info)
mainWindow.webContents.send('updateAvailable', info)
})
autoUpdater.on('update-not-available', (info) => {
// 检查到无新版本
// 提醒用户当前版本已经是最新版,无需更新
})
autoUpdater.on('download-progress', function (progressObj) {
// 更新进度条
mainWindow.webContents.send('downloadProgress', progressObj)
})
autoUpdater.on('error', (err) => {
// 自动升级遇到错误
})
autoUpdater.on('update-downloaded', (ev, releaseNotes, releaseName) => {
// 自动升级下载完成
// 可以询问用户是否重启应用更新,用户如果同意就可以执行 autoUpdater.quitAndInstall()
mainWindow.webContents.send('isUpdateNow')
})
}
ipcMain.on("checkForUpdate",() => {
console.log(autoUpdater.currentVersion)
autoUpdater.currentVersion = package_json.version;
//执行自动更新检查
autoUpdater.checkForUpdates();
})
ipcMain.on("downloadUpdate",() => {
try {
// 更新前删除本地更新包
deleteFile(autoUpdater.app.baseCachePath)
}catch {
}
//执行自动更新检查
autoUpdater.downloadUpdate();
})
ipcMain.on("quitAndInstall",() => {
//执行自动更新检查
autoUpdater.quitAndInstall();
})
背景
我们用Electron开发了桌面应用, 项目同时也在不断更新迭代。我们希望只要发布了最新的版本,用户就能够收到更新提示从而进行升级。调研了市面上的实现方式后决定采取electron-updater插件来实现更新功能。electron-updater只需要简单的文件托管,不需要专用的服务器就能实现更新。
开始
我们先用脚手架新建一个空项目(vue)
配置
publish 发布地址
如果是vue-cli-plugin-electron-builder打包则会报错如下: Question||'build' in the application package.json is not supported since 3.0 因为3.0后不支持json的方式, 需要移除package.json “build”
vue.config.js 添加builderOptions 后续需要在vue中使用ipcRenderer(主进程与渲染进程通信) 所以需要设置 // nodeIntegration: true
background.js 初始化 autoUpdater
打包测试
package.json
版本号 1.0.1
执行打包
打包后release目录 (当前为mac打包)
搭建静态服务
这里使用koa koa-static 配置静态目录
我们把demo-1.0.1-mac.zip / latest-mac.yml / 更新日志 放入更新目录public
server.js
回到项目
background.js
app.vue
点击按钮, 控制台打印如下
autoUpdater.downloadUpdate(); // 下载更新 autoUpdater.quitAndInstall(); // 执行推出安装更新 依次执行后实现了更新操作, 当然这对用户来说非常不友好,需要把更新流程交给用户去控制。
autoUpdater给我们提供 download-progress(更新进度)、update-downloaded(更新完成) 监听。
app.vue
background.js
最终效果