ruoyi-vue | electron打包教程(超详细)

这篇具有很好参考价值的文章主要介绍了ruoyi-vue | electron打包教程(超详细)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

公司项目由于来不及单独做客户端了,所以想到用electron直接将前端打包程exe,dmg等格式的安装包。
由于使用的ruoyi-vue框架开发,所以这篇教程以ruoyi-vue为基础的。

环境说明

  1. nodejs:v16.18.1
  2. npm:8.19.2
  3. ruoyi-vue:3.8.6

环境部署

下载若依并安装依赖

ruoyi-vue:https://gitee.com/y_project/RuoYi-Vue

# 进入项目目录
cd ruoyi-ui

# 安装依赖 强烈建议不要用直接使用
# cnpm 安装,会有各种诡异的 bug
# 可以通过重新指定 registry 来解决 npm 安装速度慢的问题。
npm install --registry=https://registry.npmmirror.com

安装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

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

修改ruoyi-vue相关配置/代码(很重要)


在修改前建议使用git的朋友另外起一个分支,没有用git的朋友备份一份代码。
因为你的应用应该不止是提供客户端还需要提供web端,经过下面的修改操作有部分功能将会不太适合web端。切记!!


修改.env.production生产环境配置

(如果不改调用的接口的前缀将变成本地目录)

找到这段配置:

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

如果项目web前端没有部署改为线上后端地址:

VUE_APP_BASE_API = 'http://localhost:8080'

如果项目web前端已经部署可写改为:

VUE_APP_BASE_API = 'http://IP/prod-api'

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

注释掉v-clipboard 文字复制剪贴

(为了解决clipboard报错)

找到:ruoyi-ui/src/directive/module/clipboard.js,然后全部注释掉。

修改 vue.config.js 配置

(不修改会找不到静态资源和接口无法访问)

位置:ruoyi-ui/vue.config.js

# 修改静态资源路径
publicPath: './',
 
# 修改为实际接口地址
target: `http://localhost:8080`

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

修改路由配置(按需)

(如果出现菜单栏跳转404,部分无法跳转问题)

找到:ruoyi-ui/src/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
})

全局修改Cookies为localStorage(重要)

(如果不修改,登录等使用Cookies的场景将无法继续,比如登录无法跳转到主页面。)

  1. 全局搜索Cookies.get并替换为localStorage.getItem
    ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

  2. 全局搜索Cookies.set并替换为localStorage.setItem

    然后找到:ruoyi-ui/src/views/login.vue

将:

localStorage.setItem("username", this.loginForm.username, { expires: 30 });
localStorage.setItem("password", encrypt(this.loginForm.password), { expires: 30 });
localStorage.setItem('rememberMe', this.loginForm.rememberMe, { expires: 30 });

替换为:

localStorage.setItem("username", this.loginForm.username);
localStorage.setItem("password", encrypt(this.loginForm.password));
localStorage.setItem('rememberMe', this.loginForm.rememberMe);

也就是把过期时间删掉了。

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

  1. 全局搜索Cookies.remove并替换为localStorage.removeItem

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

全局修改path.resolve为path.posix.resolve

(为了解决菜单栏跳转为404的问题)

electron中的路由跳转路径解析path.resolve结果与在浏览器中的web项目解析结果不一致

path 模块的默认操作会因 Node.js 应用程序运行所在的操作系统而异。 具体来说,当在 Windows 操作系统上运行时, path模块会假定正被使用的是 Windows 风格的路径。

path.posix 属性提供对 path 方法的 POSIX 特定实现的访问。(意思就是无视操作系统的不同,统一为 POSIX方式,这样可以确保在任何系统上结果保持一致)

全局搜索path.resolve并替换为path.posix.resolve

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

修复无法退出登录问题

(主要修改一下退出登录后跳转的页面)

位置:ruoyi-ui/src/layout/components/Navbar.vue
找到:

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(() => {});
    }

package.json新增electron打包配置

位置:ruoyi-ui/package.json

找到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"

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

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"),
    },
  },

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

electron配置

新增background.js

src新建background.js

(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()
  win.webContents.openDevTools()
  ipcMain.on('getPrinterList', (event) => {
    //主线程获取打印机列表
    win.webContents.getPrintersAsync().then(data=>{
      win.webContents.send('getPrinterList', data);
    });
    //通过webContents发送事件到渲染线程,同时将打印机列表也传过去

  });

  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')


  }
}

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

引入background.js

位置:ruoyi-ui/package.json
新增:"main": "background.js",
ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

执行打包

npm run electron:build 

打包完成后会生成:dist_electron目录

ruoyi-vue | electron打包教程(超详细),前端,vue.js,electron,前端

其他

结束了,有问题可留言讨论。欢迎评论,点赞,收藏。文章来源地址https://www.toymoban.com/news/detail-525019.html

到了这里,关于ruoyi-vue | electron打包教程(超详细)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 若依(RuoYi-Vue)+Flowable工作流前后端整合教程

    此教程适合若依前后端分离项目,其他项目可以在扩展列表中进行查找。 近期公司里需要对很久以前的RuoYi-Vue前后端分离项目扩展出flowable的功能,当然这个重任也是落在了我的身上(不然也不会有这篇文章),然后我在官网看到了RuoYi-Vue-Flowable这个项目,按照文档提供的迁

    2023年04月21日
    浏览(41)
  • ruoyi-vue前端数据字典值引用与回显(列表中回显,多选框回显)

    代码:            代码:

    2024年02月03日
    浏览(37)
  • 若依管理系统RuoYi-Vue(前后端分离版)项目启动教程

    RuoYi-Vue  是一个 Java EE 企业级快速开发平台,基于经典技术组合(Spring Boot、Spring Security、MyBatis、Jwt、Vue),内置模块如:部门管理、角色用户、菜单及按钮授权、数据权限、系统参数、日志管理、代码生成等。在线定时任务配置;支持集群,支持多数据源,支持分布式事务

    2024年02月06日
    浏览(39)
  • ruoyi-vue(若依前后端分离版本)环境搭建 用idea 安装redis 后端配置 配置node环境 前端配置

    1.在https://gitee.com/y_project/RuoYi-Vue下载源码并解压至本地文件 2.将sql文件下的两个sql文件导入数据库生成表  3.在E:eclipsespaceoneRuoYi-Vue-masterruoyi-adminsrcmainresourcesapplication-druid.yml修改数据库名和密码 4.在E:eclipsespaceoneRuoYi-Vue-masterruoyi-adminsrcmainresourcesapplication.yml配置red

    2024年04月14日
    浏览(37)
  • Linux服务器部署若依(ruoyi-vue),从购买服务器到部署完成保姆级教程

    Huawei Cloud EulerOS 还是 centos7,纠结了一段时间,了解到EulerOS是对centos8的延续版本,相当于官方不对centos8继续维护了, 最后还是选 CentOS 7.9 64bit,网上可查找的工具更多且官方还在持续维护。 这里简单购买了一个月先试用一下 点击远程登录 第一步先重置密码 一定在适当的地

    2024年04月14日
    浏览(39)
  • electron打包Vue前端

    效果:electronforge可将前端静态页面打包成.exe、.deb和.rpm等,能适配各种平台 示例:Windows环境下将前端 Vue 项目打包成exe文件 打包后的 exe 文件 运行 exe 文件 一、项目准备 开源项目 RouYi 下载 本地环境 安装依赖 报错 3.1 原因:Node版本高了 3.2 修改 package.json 3.3 修改后的 pack

    2024年04月26日
    浏览(27)
  • Ruoyi-vue项目讲解

    @[TOC]若依前后端调用接口解读 若依github官方下载地址 若依gitee官方下载地址 调用前端登录界面的时候,调用的是login.vue这个文件中的created函数 这里我们查看getCode函数方法 可以看到,这里先调用了一个getCodeImg函数,然后接收到后端返回的值之后,再进行相应的处理,显示图

    2024年02月08日
    浏览(42)
  • RuoYi-Vue下载与运行

    若依官网:RuoYi 若依官方网站 鼠标放到\\\"源码地址\\\"上,点击\\\"RuoYi-Vue 前端分离版\\\"。 跳转至Gitee页面,点击\\\"克隆/下载\\\",复制HTTPS链接即可。 源码地址为:https://gitee.com/y_project/RuoYi-Vue.git 打开IDEA,选择\\\"Get from VCS\\\"。 将源码地址粘贴到URL输入框中,并选择本地项目路径,点击\\\"C

    2024年02月04日
    浏览(35)
  • 若依Ruoyi-Vue生成代码使用

    目录 一、效果一览: 二、详细步骤: ①登录若依----点击系统工具--点击代码生成模块 ②使用Navicat在若依数据库里面新建一张表单,我这示例创建了my_students表单 并为表设计字段添加数据  ③在代码生成栏导入刚才创建的my_students表 并编辑这张表  ④完成这些操作之后,点

    2024年02月05日
    浏览(34)
  • RuoYi-Vue部署服务器流程

    本文以腾讯云服务器+宝塔面板为例子,介绍RuoYi-Vue分离版本的服务器部署流程,如在部署过程中遇到问题或有什么好的建议,欢迎在评论区留言 目录 1、服务器环境配置 2、vue项目打包 2.1、前端项目打包 2.2、打包文件路径配置 2.3、前端部署测试 3、Spring Boot项目打包部署

    2024年01月15日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包