目录
- 前言
- [一、Electron 主流程集成](#一、Electron 主流程集成)
-
- [1、主进程 main.ts](#1、主进程 main.ts)
- [2、Preload 脚本 preload.ts](#2、Preload 脚本 preload.ts)
- [二、Vue 调用 Electron](#二、Vue 调用 Electron)
- 三、打包与跨平台
-
- [1、使用 electron-builder](#1、使用 electron-builder)
- 2、打包流程
- 四、实际开发注意事项
前言
项目结构:
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 回收。