最近,领导安排我调研桌面端应用与硬件对接的实现方式。经过一番思考,我总结了以下需求:
需求概述
- 跨平台的桌面应用
- 需要与硬件对接(支持各种串口协议、信号灯、电子秤、扫码枪等)
- 基础 UI 框架能力
- 路由管理
- 全局状态管理
项目要素总结
目前,我需要完成的内容包括:
- 项目构建工具(Vite)
- 基础框架能力(Vue 3)
- 跨平台能力以及底层硬件能力(Electron、nodejs)
- 集成基础 UI 框架(Ant Design)
- 打包成桌面应用(Electron Builder)
- 路由管理(Vue Router)
- 全局状态管理(Pinia)
- 其他工具(如 Axios、Sass 等)
今天我们先从创建一个基础项目和打包开始,确保项目能够运行起来。
项目我放在码云上了,地址:https://gitee.com/pearpear/electron-app-demo
展示结果
项目创建
首先,使用 Vite 创建 Vue 3 项目:
安装 Electron
在安装 Electron 之前,需要设置镜像,以避免安装失败。关于镜像的相关配置,可以参考我的博客:vite+vue+electron打包成桌面应用。
接下来,安装 Electron 及其相关依赖:
1
| yarn add electron electron-builder vite-plugin-electron
|
创建 Electron 目录
创建一个名为 electron
的目录,并在其中创建 main.js
文件,内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| const { app, BrowserWindow } = require('electron'); const { join } = require('path');
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, title: '梨的前端小屋', icon: join(__dirname, '../public/logo.ico'), });
if (process.env.VITE_DEV_SERVER_URL) { win.loadURL(process.env.VITE_DEV_SERVER_URL); win.webContents.openDevTools(); } else { win.loadFile(join(__dirname, '../dist/index.html')); 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(); });
|
配置 Vite
接下来,配置 vite.config.js
文件,内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import electron from 'vite-plugin-electron';
export default defineConfig({ base: './', plugins: [ vue(), electron({ entry: './electron/main.js', }), ], server: { port: 3000, }, });
|
配置 package.json
在 package.json
文件中,移除 "type": "module"
配置,并设置 "main": "./electron/main.js"
。同时,更新 scripts
配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| "scripts": { "electron:build": "vite build && electron-builder" }, "build": { "productName": "electron-demo", "appId": "pearpear", "copyright": "pearpear © 2025", "compression": "maximum", "asar": true, "directories": { "output": "release/" }, "win": { "icon": "./public/logo.ico", "artifactName": "${productName}-v${version}-${platform}-setup.${ext}", "target": [ { "target": "nsis" } ] } }
|
打包项目
此时,可以执行以下命令进行打包:
在 Windows 系统下,成功打包后会生成一个 .exe
文件,用户可以直接安装。
关于其他工具(如 Ant Design Vue、Vue Router、Pinia、Axios、Sass 等),在这里就不再详细介绍了。
我的微信公众号: 梨的前端小屋