Electron + Vue 3 + Vite 实践

目录

前言

项目结构:

cpp 复制代码
my-app/
├─ electron/           # Electron 主进程代码
│  ├─ main.ts
│  └─ preload.ts
├─ src/                # 前端代码 (Vue)
│  ├─ App.vue
│  └─ main.ts
├─ package.json
├─ vite.config.ts
└─ tsconfig.json

工具选择:

  • Vite:更快的 HMR,现代构建工具。
  • electron-builder:打包和发布。
  • TypeScript:提升开发体验与类型安全。

一、Electron 主流程集成

1、主进程 main.ts

cpp 复制代码
import { app, BrowserWindow } from 'electron';
import path from 'path';

let mainWindow: BrowserWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    }
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173'); // Vite Dev Server
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
  }
}

app.whenReady().then(createWindow);

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

2、Preload 脚本 preload.ts

cpp 复制代码
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electronAPI', {
  sendMessage: (msg: string) => ipcRenderer.send('message', msg),
  onMessage: (callback: (event: any, data: any) => void) => ipcRenderer.on('message-reply', callback)
});

关键点:

  • 使用 contextBridge 替代 nodeIntegration = true。
  • Renderer 只能通过安全 API 调用 Node 功能。

二、Vue 调用 Electron

采用 Vue 3 + Composition API:

cpp 复制代码
<script setup lang="ts">
const sendMsg = () => {
  window.electronAPI.sendMessage('Hello Electron');
};

window.electronAPI.onMessage((_event, data) => {
  console.log('Received:', data);
});
</script>

<template>
  <button @click="sendMsg">Send Message</button>
</template>

注意:

  • window.electronAPI 来自 Preload 安全桥接。
  • 避免直接在 Renderer 中使用 Node API。

三、打包与跨平台

1、使用 electron-builder

在 package.json 添加:

json 复制代码
"build": {
  "appId": "com.example.app",
  "directories": { "output": "release" },
  "files": ["dist/**/*", "electron/**/*"],
  "mac": { "target": "dmg" },
  "win": { "target": "nsis" },
  "linux": { "target": "AppImage" }
}
  • dist:Vite 前端打包产物
  • electron:主进程 & preload
  • 注意 macOS 需要签名 (notarize)

2、打包流程

bash 复制代码
# 前端打包
vite build

# Electron 打包
electron-builder

四、实际开发注意事项

1、开发环境:

  • 使用 concurrently 启动 Vite 和 Electron:
json 复制代码
"dev": "concurrently \"vite\" \"electron .\""

2、Renderer Node 安全:

  • 永远不要在 Renderer 中直接启用 Node。
  • 所有文件操作通过 Preload/IPC。

3、跨平台文件路径:

  • 使用 path.join,避免 Windows/Unix 路径差异。
  • 打包时注意 __dirname 的路径。

4、多窗口 / 多进程优化:

  • 渲染复杂 SPA 页面时,优先复用窗口或 BrowserView。
  • 关闭窗口时记得 win = null 回收。
相关推荐
FRing0339 分钟前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
程序员大阳44 分钟前
副队长ES6+教程(5)--模板字符串
javascript·vue.js·es6·模板字符串
鶴哥只手遮天1 小时前
# 《Electron 45.2.3 内核解剖》第 6 章 Node.js 集成:两个事件循环的婚姻
前端·electron·开源
程序员大阳1 小时前
副队长ES6+教程(4)--拓展运算符
javascript·vue.js·es6·收集·拓展运算符·展开
徐小夕2 小时前
CADViewer-Skill:让 Agent 原生支持 DWG 解析、可视化图统计、图纸导出
前端·vue.js·github
鶴哥只手遮天19 小时前
《Electron 45.2.3 内核解剖》第 4 章 补丁体系:380 个补丁改了什么
前端·electron
FungLeo21 小时前
成为全栈·Vue 管理后台篇·分类树与标签管理:层级数据如何落到管理界面
前端·javascript·vue.js·分类树·naive ui·标签管理·前端数据结构
ruanno_top1 天前
选中一项后,焦点掉回了页面顶部:三个弹层的焦点还原
vue.js
tryCbest1 天前
Vue3——第 17 篇:模板引用(ref)与组件实例——操作 DOM 的正确姿势
vue.js·前端搭建
头发还在的女程序员1 天前
Java在线租房系统源码解析:Spring Boot+Vue 3+UniApp房源管理与预约看房方案
java·vue.js·spring boot·租房小程序·租房系统·租房软件