vue3+electron搭建桌面软件

vue3+electron开发桌面软件

最近有个小项目, 客户希望像打开 网易云音乐 那么简单的运行起来系统. 前端用 Vue 会比较快一些, 因此决定使用 electron 结合 Vue3 的方式来完成该项目.

然而, 在实施过程中发现没有完整的博客能够记录从创建到打包的流程, 摸索一番之后, 随即梳理成文供大家参考.

废话不多说, 直接开始!

对了, 开始之前, 先给 Vue3 和 electron 在 package.json 中的版本号展示出来供大家参考.

"dependencies": {
  "nodemon": "^3.1.3",
  "vue": "^3.4.21"
},
"devDependencies": {
  "@vitejs/plugin-vue": "^5.0.4",
  "electron": "^31.0.0",
  "vite": "^5.2.0"
}

1, 创建 Vue3 项目

终端指令

npm init vite

创建好之后, 就是根据终端提示初始化 node_modules 了, 创建 Vue3 的项目这里就不多说了, 能看这篇文章的都是大佬了, Vue3 工程的创建应该是手到擒来的呢!

2, Vue 项目中安装 electron

终端指令

npm i electron -D

3, electron 的一些初始化配置

3.1 创建 electron 入口文件

根目录创建 electron 文件夹, 并创建 main.js 文件, 内容示例如下:

const { app, protocol, BrowserWindow, globalShortcut } = require('electron')
// 需在当前文件内开头引入 Node.js 的 'path' 模块
const path = require('path')

app.commandLine.appendSwitch('--ignore-certificate-errors', 'true')
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

const createWindow = () => {
  const win = new BrowserWindow({
    minWidth: 960,
    minHeight: 540,
    width: 960,
    height: 540,
    //窗口是否在屏幕居中. 默认值为 false
    center: true,
    //设置为 false 时可以创建一个无边框窗口 默认值为 true。
    frame: false,
    //窗口是否在创建时显示。 默认值为 true。
    show: true,
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      preload: path.join(__dirname, 'preload.js'),
      // webSecurity: false, false 是 控制台会报警告, 不太喜欢, 就设置为了 true
      webSecurity: true
    }
  })
  win.setMenu(null)// 不展示菜单
  if (app.isPackaged) {
    win.loadURL(`file://${path.join(__dirname, '../dist/index.html')}`)
  } else {
    // win.loadURL('http://127.0.0.1:5173/') 127... 这个地址的话, 运行起来会白屏, 需使用 localhost
    win.loadURL('http://localhost:5173/')
    win.webContents.openDevTools()// 打开调试工具, 上线时这行是要注释掉的
  }
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    win.webContents.openDevTools()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

3.2 在 package.json 中配置 electron

两个操作:
1, 删除: “type”: “module”, 要不然运行会报错, 因为 electron 的包都是通过 require 引入的
2, 添加: “main”: “electron/main.js”,

3.3 创建 preload.js 文件

在 electron 文件夹中创建 preload.js 文件, 内容示例如下(如果不需要也可以不创建, 不创建时 main.js 中的 preload 属性也不需要配置):

// 所有的 Node.js API接口 都可以在 preload 进程中被调用.
// 它拥有与Chrome扩展一样的沙盒。
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})

4, 配置启动命令

建议使用 nodemon 来进行热更新, 谁用谁爽!

4.1 安装 nodemon

终端指令

npm i nodemon

4.2 配置 package.json 文件

在 scripts 属性下配置以下内容:

"start": "vite | nodemon --exec electron . --watch ./ --ext .js,.html,.css,.vue"

5, 启动项目

终端指令

npm start

6, 安全策略

经过以上 五步 的操作, 正常情况下你的项目就会启动起来了, 只不过可能会在控制台报一个警告, 内容大致如下:

Electron Security Warning (Insecure Content-Security-Policy) This renderer process has either no Content Security
  Policy set or a policy with "unsafe-eval" enabled. This exposes users of
  this app to unnecessary security risks.

For more information and help, consult
https://electronjs.org/docs/tutorial/security.
This warning will not show up
once the app is packaged.

是安全策略的设置告警,意思是内容安全策略没有设置,或者使用了unsafe-eval的安全设置,只需在index.html文件中设置安全策略即可。
其实, 程序员是忽略警告的, 不过你如果有和我一样的强迫症, 可以在 index.html 文件中添加以下内容来清除次警告:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">

meta 标签, 不用我说添加到哪里了吧?

好了, 到此呢, 项目就能够正常启动开发了, 文章到此暂告一个段落, 后续补充 electron 打包的章节!
附上关键程序截图:
关键代码截图

接下来我们继续聊 electron 打包的问题

7, electron 打包

7.1, 安装electron打包开发依赖

终端指令

npm install --save-dev electron-builder

7.2, 配置 package.json 文件

在package.json添加 author、description、build 字段,同时在 scripts 字段添加 electron:build 命令. 完整 package.json 配置示例:

{
  "name": "new-project",
  "private": true,
  "version": "0.0.0",
  "main": "electron/main.js",
  "author": "CorderLeoD",
  "description": "Hello World!",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "start": "vite | nodemon --exec electron . --watch ./ --ext .js,.html,.css,.vue",
    "electron:build": "vite build && electron-builder"
  },
  "dependencies": {
    "nodemon": "^3.1.3",
    "vue": "^3.4.21"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.0.4",
    "electron": "^31.0.0",
    "electron-builder": "^24.13.3",
    "vite": "^5.2.0"
  },
  "build": {
    "appId": "cc11001100.electron.example-001",
    "copyright": "CC11001100",
    "productName": "example-001",
    "directories": {
      "buildResources": "build",
      "output": "electron_dist"
    },
    "nsis": {
      "oneClick": false,
      "language": "2052",
      "perMachine": true,
      "allowToChangeInstallationDirectory": true
    },
    "dmg": {
      "background": "build/background.png",
      "icon": "build/icons/icon.icns",
      "iconSize": 100,
      "contents": [
        {
          "x": 380,
          "y": 180,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 130,
          "y": 180,
          "type": "file"
        }
      ],
      "window": {
        "x": 100,
        "y": 100,
        "width": 500,
        "height": 300
      }
    },
    "mac": {
      "target": [
        "dmg",
        "zip"
      ],
      "category": "public.app-category.utilities"
    },
    "win": {
      "icon": "build/icons/food.png",
      "target": {
        "target": "nsis",
        "arch": [
          "x64",
          "ia32"
        ]
      }
    },
    "asar": false,
    "files": [
      "./dist",
      "./electron",
      "!**/node_modules/**"
    ],
    "extends": null
  }
}

注: 关于 build 的具体配置, 不在一一列举, 大家自行搜索吧!

7.3, 完善打包所需资源

在 7.2 的 build 属性中会有 background, icon 等需要的图片资源, 其实就是程序安装后的图标, 按照上述示例, 需要在项目根目录创建 build 文件夹, 而后在 build 文件夹中创建 icons 文件夹, 然后放入对应图片资源.
注意:windows系统中icon需要256*256的ico格式图片

7.4, 配置 vite.config.js

添加 base: “./”
修改打包文件的引入路径的, 要不然打包后打开应用程序会白屏.
示例代码:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  plugins: [vue()],
})

7.5 打包

终端指令:

npm run electron:build

初次打包, 时间会比较久, 因为需要从 GitHub 下载资源, 这个时候你可以打开浏览器访问 GitHub 看能不能访问, 如果不能访问, 打包大概率会失败, 网络超时了.

8, 一个问题

有一个问题, 需要特别说明, electron 需要自己一个特殊的镜像, 即使你切换淘宝源, 也可能会有问题, 这个情况伴随 electron 使用的整个过程, 不单单是在打包环节.

这个问题可能发生在你安装 electron 的时候, 或者 安装 electron-builder 的时候, 或者 打包 的时候, 怎么解决呢?

找到 .npmrc 文件, 添加下面一行内容即可:

electron_mirror=https://npmmirror.com/mirrors/electron/

9, 启动项目

步骤 7.5 打包指令会默认打包对应平台的安装包 (就是你电脑系统环境对应的安装包), 你可以在 package.json 文件的 script 属性 打包指令的配置后面添加参数来打一个指定操作系统的安装包.

找到 electron_dist 文件夹中的安装包, 安装之后, 双击启动项目吧!

最后再安排个项目截图:
electron打包项目

Vue 的 logo 裂了, 不再处理了, O(∩_∩)O哈哈~

本章完!

  • 13
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值