开发喵星球

若依分离版集成Electron打包exe应用程序(338)

1. 修改 package.json 文件,增加必要依赖与配置

{
  "name": "ruoyi",
  "version": "3.8.6",
  "description": "若依管理系统",
  "author": "若依",
  "license": "MIT",
  "main": "background.js",
  "scripts": {
    ....
    "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-devtools-installer": "3.2.0",
    "electron-store": "8.1.0",
    "vue-cli-plugin-electron-builder": "2.1.1",
    ....
  },
  "devDependencies": {
    ....
    "electron": "26.2.0",
    ....
  },
  ....
}

2. 配置后端接口地址

修改 .env.production 文件中 VUE_APP_BASE_API 属性为你的后端接口地址

VUE_APP_BASE_API = 'https://vue.ruoyi.vip/prod-api'

3. 在 ruoyi-ui/src 下创建 background.js 文件

'use strict'

import { app, protocol, BrowserWindow } 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 additionalData = { myKey: 'myValue' }
let myWindow = null

// 在应用准备前必须先注册协议
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  // 创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // 开发模式下加载开发服务器的URL
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // 非开发模式下加载应用
    win.loadURL('app://./index.html')
  }
}

const gotTheLock = app.requestSingleInstanceLock(additionalData)
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', () => {
    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore()
      myWindow.focus()
    }
  })

  // 当所有窗口关闭时退出应用(非macOS)
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

  // 在应用被激活时重新创建窗口(macOS)
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
      try {
        await installExtension(VUEJS_DEVTOOLS)
      } catch (e) {
        console.error('Vue Devtools 安装失败:', e.toString())
      }
    }
    createWindow()
  })

  if (isDevelopment) {
    if (process.platform === 'win32') {
      process.on('message', (data) => {
        if (data === 'graceful-exit') {
          app.quit()
        }
      })
    } else {
      process.on('SIGTERM', () => {
        app.quit()
      })
    }
  }
}

4. 修改代码以适配 Electron 应用

修改 layout/components/Navbar.vueutils/request.js 文件,将 location.href = '/index' 替换为 this.$router.push('/login')

this.store.dispatch('LogOut').then(() => {
    this.router.push('/login');
})

router/index.js 中,将 mode: 'history' 改为 mode: 'hash'

export default new Router({
  mode: 'hash',
  ...
})

5. 将项目中的 cookie 替换为 localStorage

5.1 在 package.json 中删除 cookie 相关依赖

"js-cookie": "3.0.1",

并在 main.jsstore/modules/app.jsutils/auth.jslogin.vue 中移除 import Cookies from 'js-cookie' 的导入。

5.2. 替换 main.jsCookies.getlocalStorage.getItem

Vue.use(Element, {
  size: localStorage.getItem('size') || 'medium' 
})

5.3 在 utils/auth.js 中将 Cookies 方法替换为 localStorage

const TokenKey = 'Admin-Token'

export function getToken() {
  return localStorage.getItem(TokenKey)
}

export function setToken(token) {
  return localStorage.setItem(TokenKey, token)
}

export function removeToken() {
  return localStorage.removeItem(TokenKey)
}

5.4 store/modules/app.js 中相应修改为 localStorage

const state = {
  sidebar: {
    opened: localStorage.getItem('sidebarStatus') ? !!+localStorage.getItem('sidebarStatus') : true,
    withoutAnimation: false,
    hide: false
  },
  device: 'desktop',
  size: localStorage.getItem('size') || 'medium'
}

5.5 在 login.vue 文件中替换 Cookies 相关逻辑为 localStorage

getCookie() {
  const username = localStorage.getItem("username");
  const password = localStorage.getItem("password");
  const rememberMe = localStorage.getItem('rememberMe')
  this.loginForm = {
    username: username === null ? this.loginForm.username : username,
    password: password === null ? this.loginForm.password : decrypt(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  };
},

6. 安装所需依赖

执行以下命令安装项目的依赖:

npm install --registry=https://registry.npmmirror.com

7. 打包应用程序

运行以下命令进行打包操作:

npm run electron:build

打包完成后,生成的 .exe 文件将位于 dist_electron 目录中,双击文件即可安装。
如果安装失败,建议配置镜像地址后使用 cnpm 单独安装 Electron 相关依赖。

# 配置 Electron 镜像地址
npm config set registry http://registry.npm.taobao.org/
npm config set electron_mirror="https://npm.taobao.org/mirrors/electron/"
npm config set electron_builder_binaries_mirror="http://npm.taobao.org/mirrors/electron-builder-binaries/"

# 安装 Electron
cnpm install electron --save-dev

# 安装 Electron 开发者工具管理插件
cnpm install electron-devtools-installer


# 安装 Electron 数据持久化存储插件
cnpm install electron-store

# 安装 Electron 打包和构建插件
cnpm install vue-cli-plugin-electron-builder
   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-09-21 16:41:53 阅读量:135
<<   >>


powered by kaifamiao