Vue2项目中使用electron打包Windows桌面应用(全教程、踩坑集合)

Vue2项目中使用electron打包Windows桌面应用(全教程、踩坑集合),第1张

目录

一、开发环境(因为环境踩了太多坑 最后成功的环境都是一个一个试出来的。。。)

二、开发流程(serve + build + 基础设置 + 系统托盘)

三、设置桌面以及exe安装包的图标

四、优化npm run electron:serve编译的速度


一、开发环境(因为环境踩了太多坑 最后成功的环境都是一个一个试出来的。。。)

node:14.18.1

electron:12.0.0

二、开发流程(serve + build + 基础设置 + 系统托盘)

1、添加electron-builder

在项目目录下运行命令:vue add electron-builder 

注:(node版本14-16推荐选择12.0.0、16以上可以试着选择13.0.0、不过我没有试过。。。不知道可不可行)

问题一来了???输入vue add electron-builder 可能会没反应

解决办法

vue/cli卸载重装 再运行vue add electron-builde

卸载命令:npm uninstall -g @vue/cli

安装命令:npm install -g @vue/cli


PS:vue add electron-builder下载electron时可能会失败,推荐使用淘宝镜像下载:cnpm i electron

2、运行:npm run electron:serve

如果遇到这段而导致serve自动停掉(tips:请关机重启。。。因为我百度了一早上 结果关机重启就能跑起来了。。。我真的会谢,简直离了个大谱)

3、打 包:npm run electron:build(大概率网络原因 会下载失败 详解见下)

根据自己的报错信息下载对应文件放置于以下文件目录内

 

4、下面贴上我background.js的配置。。。( 仅供参考 )

'use strict'

import { app, protocol, BrowserWindow,Tray,Menu,dialog,remote } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
const path = require('path')
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
let win;
//托盘对象
let appTray = null;
async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1400,
    height: 800,
    // 应用窗口名称
    title: 'xxx',
    // 应用窗口图标 ( __static 相当于根目录下的public)
    icon:path.join(__static,'icon.ico'),
    // webPreferences: {
    //   preload: path.join(__static, 'preload.js')
    // }
  })

  // 设置系统托盘图标 提示title
  appTray = new Tray(path.join(__static, 'icon.ico'));
  appTray.setToolTip('提示文字');
  
  //单击右下角小图标显示应用
  appTray.on('click',function(){
    win.show();
  })
  //系统托盘右键菜单
  var trayMenuTemplate = [
    {
      label: '退出',
      click: function () {
        app.exit();
        app.exit();//因为程序设定关闭为最小化,所以调用两次关闭,防止最大化时一次不能关闭的情况
      }
    }
  ];
    
  // 打开调试模式
  // win.webContents.openDevTools()
  //图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  //设置此图标的上下文菜单
  appTray.setContextMenu(contextMenu);
  
  //左上角菜单栏
  const template = [
      {
          label: '文件',
          submenu: [
              { label: '刷新',role: 'reload' },
              { label: '关闭',role: 'close' }
          ]
      },
      {
        label: '编辑',
        submenu: [
          { label: '缩小',role: 'zoomOut' },
          { label: '放大',role: 'zoomIn' },
          { label: '默认大小',role: 'resetZoom' }
        ]
      }
  ]
  //把模板添加到Menu菜单中
  let m = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(m);
  更多参数设置参考官网:http://www.kaotop.com/file/tupian/20220526/托盘图标闪烁  var count = 0;  setInterval(function() {    if (count   % 2 == 0) {      appTray.setImage(path.join(__static, 'icon.png'));
    } else {
      //透明图标
      //注:没有透明图片的话可以通过appTray.setImage(nativeImage.createFromPath(null))来设置
      appTray.setImage(path.join(__static, 'transparent.png'));
    }
  }, 400);

  //关闭窗口d出提示
  // win.on("close", (e) => {
  //   dialog.showMessageBox({
  //     type:'info',
  //     title: '提示',
  //     message:"关闭窗口时",
  //     buttons:['小化到托盘',"退出"],
  //   })
  //       .then(data => {
  //         if (data.response == 1) {
  //           app.exit()
  //         }else {
  //           win.minimize();
  //         }
  //       })
  // })
  win.on('close',(e) => {
    //回收BrowserWindow对象
    if(win.isMinimized()){
        app.exit()
    }else{
        e.preventDefault();
        win.hide();
    }
  });
  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)
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    // 线上
    win.loadURL('https://xxx.com')
  }
}

// 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.exit()
  }
})

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())
    }
  }
  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()
    })
  }
}
三、设置桌面以及exe安装包的图标

参考这篇 blog

四、优化npm run electron:serve编译的速度
//在项目根目录下运行
​​​​​​​node --cpu-prof --heap-prof -e "require('is-online')"

欢迎各位同行找我探讨 一起进步!!!
 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1321655.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存