Vue cli 3.x使用electron打包配置

1. 安装依赖包

npm install electron electron-updater vue-cli-plugin-electron-builder --save-dev

2. package.json修改

1、scripts中添加
“electron:build”: “vue-cli-service electron:build”,
“electron:serve”: “vue-cli-service electron:serve”,
“postinstall”: “electron-builder install-app-deps”,
“postuninstall”: “electron-builder install-app-deps”

2、增加一行
main: ‘background.js’ (代码如下,src目录下新增background.js文件)

'use strict'

import { app, protocol, BrowserWindow, Menu, globalShortcut } from 'electron'
import {
  createProtocol,
  installVueDevtools
} from 'vue-cli-plugin-electron-builder/lib'
                
const fs = require('fs')
const autoUpdater = require("electron-updater").autoUpdater
const isDevelopment = process.env.NODE_ENV !== 'production'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
let preventQuit = false                 // 阻止窗口关闭

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

// windows: app.ico 最小尺寸:256x256
// macOS: app.png 或 app.icns 最小尺寸:512x512 
// 这里的${__static}对应的是public目录
function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    show: false,
    width: 1200,
    height: 720,
    icon: `${__static}/app.ico`,
    webPreferences: {
      webSecurity: false,    // 取消跨域限制
      nodeIntegration: true
    }
  })

  // 窗口最大化
  win.maximize()
  win.show()

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  win.on('close', (e) => {
    if(preventQuit) {
      e.preventDefault()                
    }
  })

  win.on('closed', () => {
    win = null
  })

  createMenu()
}

function createMenu() {
  // darwin表示macOS,针对macOS的设置
  if (process.platform === 'darwin') {
    const template = [{
      label: '应用标题',
      submenu: [
        {
          role: 'about'
        },
        {
          role: 'quit'
        }
      ]
    }]
    let menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    // windows及linux系统
    Menu.setApplicationMenu(null)
  }
}

// 开机自启动
// app.setLoginItemSettings({
//   openAtLogin: true
// })

// 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 (win === null) {
    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 installVueDevtools()
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }

  globalShortcut.register('CommandOrControl+Shift+i', function () {
    win.webContents.openDevTools()
  })

  createWindow()
  
  // 自动升级的代码
  // process.env.VUE_APP_BASE_FILE + '/profile/upload/updatePackage' 这里为与后端协商好的上传安装包和latest.yml的文件地址
  autoUpdater.setFeedURL(process.env.VUE_APP_BASE_FILE + '/profile/upload/updatePackage')
  autoUpdater.checkForUpdates()
  autoUpdater.on('error', function (error) {
    console.log('error')
  })
  autoUpdater.on('update-available', function (info) {
    console.log('发现新版本')
  })
  autoUpdater.on('update-not-available', function (info) {
    console.log('当前是最新版本')
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) 	   {
    autoUpdater.quitAndInstall();
  })
})

// 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()
    })
  }
}
3.安装包的升级,electron的autoUpdater支持windows和ios平台的升级。
  1. 打出安装包和最新的latest.yml文件
  2. 上传安装包和latest.yml文件到服务器
  3. 使用autoUpdater实现自动检测更新,检测服务器上的latest.yml文件,检测到有新版本时下载安装即可

首先在vue.config.js中添加electron-builder的打包配置,并添加publish的配置,配置了publish才能打包出latest.yml文件,其中publish中的url属性对应上传文件的服务器地址

 pluginOptions: {
    electronBuilder: {
      builderOptions: {
        productName: '应用标题',
        win: {
          icon: './public/app.ico'
        },
        mac: {
          icon: './public/app.png'
        },
        nsis: {
          oneClick: true,
          createDesktopShortcut: true,
          createStartMenuShortcut: true
        },
        publish: [
          {
            "provider": "generic",
            "url": process.env.VUE_APP_BASE_FILE + "/profile/upload/updatePackage",
            "channel": "latest"
          }
        ]
      }
    }
  }

在background.js中调用autoUpdater,调用autoUpdater.setFeedURL(url)检测latest.yml文件,这里的setFeedURL的参数url即对应上面的publish中的url

  const autoUpdater = require("electron-updater").autoUpdater
	
  // process.env.VUE_APP_BASE_FILE + '/profile/upload/updatePackage' 这里为与后端协商好的上传安装包和latest.yml的文件地址
  autoUpdater.setFeedURL(process.env.VUE_APP_BASE_FILE + '/profile/upload/updatePackage')
  autoUpdater.checkForUpdates()
  autoUpdater.on('error', function (error) {
    console.log('error')
  })
  autoUpdater.on('update-available', function (info) {
    console.log('发现新版本')
  })
  autoUpdater.on('update-not-available', function (info) {
    console.log('当前是最新版本')
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) 	   {
    autoUpdater.quitAndInstall();
  })
})

4. 更改路由模式(electron模式下需要修改为hash模式),否则打包出来打开首页可能会一片空白
5. 如需要考虑登录,原来如果是将token存在cookie中的需将缓存token的cookie方式更改为sessionStorage或localStorage
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值