vue项目,若依使用electron打包为exe应用

本文介绍了如何在Node.js环境中使用npm安装Electron相关插件,如开发者工具、数据存储库,并在VueCLI项目中集成Electron构建。还涵盖了打包设置、路由问题修复以及必要的配置调整,如全局修改cookies为localStorage和处理生产环境配置。
摘要由CSDN通过智能技术生成
  1. 环境准备
    nodejs: v16.18.1
    npm: 8.19.2

  2. electron相关插件

    # electron
    npm install electron
    
    # 在 Electron 应用程序中安装和管理开发者工具
    npm install electron-devtools-installer
    
    # 简单的持久化数据存储库
    npm install electron-store
    
    # 在 Vue CLI 项目中集成 Electron 打包和构建
    npm install vue-cli-plugin-electron-builder
    

    若是安装报错,请检查环境配置

    # electron
    npm install electron --registry=https://registry.npmmirror.com
    
    # 在 Electron 应用程序中安装和管理开发者工具
    npm install electron-devtools-installer --registry=https://registry.npmmirror.com
    
    # 简单的持久化数据存储库
    npm install electron-store --registry=https://registry.npmmirror.com
    
    # 在 Vue CLI 项目中集成 Electron 打包和构建
    npm install vue-cli-plugin-electron-builder --registry=https://registry.npmmirror.com
    

    若是还是报错报镜像问题,尝试更改为如下官方给出的镜像或是检查网络问题,建议使用科学上网。

    npm config set disturl=https://registry.npmmirror.com/-/binary/node
    
    npm config set ELECTRON_MIRROR=https://registry.npmmirror.com/-/binary/electron/
    
    yarn config set disturl https://registry.npmmirror.com/-/binary/node -g
  3. 修改.env.production生产环境配置(如果不改,接口的前缀将变成本地目录)
     

    # 若依管理系统/生产环境
    VUE_APP_BASE_API = '/prod-api'

    替换为

    VUE_APP_BASE_API = 'http://项目部署地址/prod-api'
    

    若还是出现此类问题,则直接去修改 project/src/utils/request.js 文件

    直接将其修改为线上地址

  4. 路由跳转 404 问题,修改 router/index.js 文件

    # 原配置
    export default new Router({
      mode: 'history', // 去掉url中的#
      scrollBehavior: () => ({ y: 0 }),
      routes: constantRoutes
    })
    
    # 改为:
    # 路由模式改为hash意味着在URL中使用hash(#)来表示路由路径
    export default new Router({
      mode: 'hash', // 去掉url中的#
      scrollBehavior: () => ({ y: 0 }),
      routes: constantRoutes
    })
    
    
    # 若还是出现此类问题
    # 直接讲mode注释了
    
    #再去全局修改path.resolve为path.posix.resolve(大多数文档是这样说,但我实际运用过程中这样还是出现了跳转404问题),我的解决方案是 找到 project/src/layout/components/Sidebar/SidebarItem 讲此方法修改至如下
     resolvePath(routePath) {
        if (isExternal(routePath)) {
            return routePath
        }
        if (isExternal(this.basePath)) {
            return this.basePath
        }
        // return path.resolve(this.basePath, routePath)
        let url = this.basePath+'/'+routePath //兼容exe路由跳转 fxh 2024.04.23
        return url
    }
    
  5. 全局修改Cookies为localStorage(重要)

    #全局搜索并修改
    Cookies.get =======> localStorage.getItem
    Cookies.set =======> localStorage.setItem
    Cookies.remove =======> localStorage.removeItem
  6. 退出登录不跳转问题

    async logout() {
          this.$confirm('确定注销并退出系统吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('LogOut').then(() => {
              location.href = '/index';
            })
          }).catch(() => {});
        }
    
    修改至如下
    
    async logout() {
          this.$confirm('确定注销并退出系统吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('LogOut').then(() => {
              this.$router.push('/login')
            })
          }).catch(() => {});
        }
    
  7. 在 package.json 中添加如下配置

    "electron:serve": "vue-cli-service electron:serve",
    "electron:build": "vue-cli-service electron:build",
    "electron:build:win32": "vue-cli-service electron:build --win --ia32"
    


    注意: 请把 dependencies 中的electron相关配置移到 devDependencies 中·,否则会报错,效果如下:

  8. vue.config.js添加打包配置
    module.exports中添加以下配置:(根据自己的需求进行修改)

      pluginOptions: {
        electronBuilder: {
          // preload: 'src/preload.js',
          nodeIntegration: true,
          contextIsolation: false,
          enableRemoteModule: true,
          publish: [{
            "provider": "xxxx有限公司",
            "url": "http://xxxxx/"
          }],
          "copyright": "Copyright © 2022",
          builderOptions:{
            appId: 'com.ruoyi',
            productName: 'ruoyi',
            nsis:{
              "oneClick": false,
              "guid": "idea",
              "perMachine": true,
              "allowElevation": true,
              "allowToChangeInstallationDirectory": true,
              "installerIcon": "build/app.ico",
              "uninstallerIcon": "build/app.ico",
              "installerHeaderIcon": "build/app.ico",
              "createDesktopShortcut": true,
              "createStartMenuShortcut": true,
              "shortcutName": "若依管理系統"
            },
            win: {
              "icon": "build/app.ico",
              "target": [
                {
                  "target": "nsis",			//使用nsis打成安装包,"portable"打包成免安装版
                  "arch": [
                    "ia32",				//32位
                    "x64" 				//64位
                  ]
                }
              ]
            },
          },
          // preload: path.join(__dirname, "/dist_electron/preload.js"),
        },
      },
    
  9. 新建 backfground.js 文件 并引入

    # 在  package.json 中添加
      "main": "background.js",
    
    '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 isDevelopment = process.env.NODE_ENV !== 'production'
    const Store = require('electron-store');
    
    // 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.
      const win = 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
          contextIsolation:false,     //上下文隔离
          enableRemoteModule: true,   //启用远程模块
          nodeIntegration: true, //开启自带node环境
          webviewTag: true,     //开启webview
          webSecurity: false,
          allowDisplayingInsecureContent: true,
          allowRunningInsecureContent: true
        }
      })
      win.maximize()
      win.show()
      ipcMain.on('getPrinterList', (event) => {
        //主线程获取打印机列表
        win.webContents.getPrintersAsync().then(data=>{
          win.webContents.send('getPrinterList', data);
        });
        //通过webContents发送事件到渲染线程,同时将打印机列表也传过去
    
      });
      // 这段代码可以删除exe菜单栏
      win.setMenu(null);
      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)
        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.loadURL(`file://${__dirname}/index.html`);//在窗口内要展示的内容index.html 就是打包生成的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 () => {
      Store.initRenderer();
      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()
        })
      }
    }
    
  10. 执行打包,命令


    参考文档:ruoyi-vue | electron打包教程(超详细)_若依前端打包-CSDN博客

  11. 创作不易,欢迎点赞转发及指正
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===
    文档结尾分隔符==================================================-===

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值