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

目录

 

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

二、开发流程(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-builder

卸载命令: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);
  更多参数设置参考官网:https://www.electronjs.org/zh/docs/latest/api/menu

  //托盘图标闪烁
  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);

  //关闭窗口弹出提示
  // 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')"

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

  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
对于给已有的 Vue 项目打包Electron 应用,你可以按照以下步骤进行操作: 1. 首先,确保你的 Vue 项目已经能够正常运行并且已经安装了 Electron 相关依赖。 2. 在项目根目录下创建一个 `main.js` 文件,这将是 Electron 应用的入口文件。在该文件,你需要创建一个 Electron 应用窗口并加载 Vue 项目打包文件。 ```javascript const { app, BrowserWindow } = require('electron'); function createWindow() { // 创建浏览器窗口 const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); // 加载 Vue 项目打包文件 win.loadURL(`file://${__dirname}/dist/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(); }); ``` 3. 接下来,在 `package.json` 文件添加一个 `start` 命令,用于启动 Electron 应用。 ```json { "scripts": { "start": "electron ." } } ``` 4. 然后,运行 `npm start` 命令启动 Electron 应用,确保应用能够正常运行。 5. 最后,使用 Electron 打包工具将整个项目打包成可执行文件。常用的打包工具有 `electron-packager` 和 `electron-builder`,你可以根据自己的需求选择其一个进行使用。 例如,使用 `electron-builder` 进行打包,首先安装该工具: ```bash npm install electron-builder --save-dev ``` 然后在 `package.json` 文件添加以下配置: ```json { "build": { "appId": "com.example.myapp", "productName": "MyApp", "directories": { "output": "dist" }, "files": [ "dist/**/*", "main.js" ], "mac": { "target": "dmg" }, "win": { "target": "nsis" } } } ``` 最后,运行以下命令进行打包: ```bash npm run build ``` 打包完成后,你会在 `dist` 目录下找到相应的可执行文件和安装包。 希望这些步骤能帮助到你!如有其他问题,请随时提问。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值