1. Electron 背景介紹
Electron 是一個開源框架,由 GitHub 開發(最初為 Atom 編輯器 項目構建),允許開發者使用 Web 技術(HTML、CSS、JavaScript) 構建 跨平台桌面應用程序。
1.1 起源與發展
- 2013年:最初名為 Atom Shell,是 GitHub 為其代碼編輯器 Atom 開發的底層框架。
- 2015年:更名為 Electron,並開源,迅速被 Slack、Visual Studio Code、Discord 等知名應用採用。
- 2022年:底層升級至 Chromium 106 和 Node.js 16.16.0,並支持 Windows 沉浸式黑暗模式 等新特性。
1.2 核心特點
✅ 跨平台:一套代碼可運行在 Windows、macOS、Linux 上。
✅ Web 技術驅動:使用 HTML、CSS、JavaScript 構建 UI,無需學習 C++/Objective-C/Java。
✅ Chromium + Node.js:
- Chromium 提供現代化的 Web 渲染引擎(支持最新 Web API)。
- Node.js 允許訪問 文件系統、網絡、原生 API 等底層功能。
✅ 生態豐富: - 支持 自動更新、打包安裝(NSIS、DMG、AppImage)。
- 被 VS Code、Figma、Trello Desktop 等流行應用使用。
2. Electron 架構
Electron 應用由兩個核心進程組成:
2.1 主進程(Main Process)
- 作用:控制應用生命週期(啓動、退出)、創建窗口、管理原生功能(菜單、對話框)。
- 運行環境:Node.js + Electron API。
- 關鍵模塊:
app(控制應用事件)BrowserWindow(創建窗口)dialog(文件/消息對話框)ipcMain(與渲染進程通信)
2.2 渲染進程(Renderer Process)
- 作用:負責 UI 渲染(HTML/CSS/JS),類似瀏覽器標籤頁。
- 運行環境:Chromium(支持 Web 技術) + 可選 Node.js(需配置)。
- 關鍵模塊:
ipcRenderer(與主進程通信)fetch/XMLHttpRequest(網絡請求)
🔗 進程通信(IPC):
主進程和渲染進程通過 ipcMain 和 ipcRenderer 進行數據交換。
3. 環境搭建(Vue3 + Electron)
3.1 創建 Vue3 項目
# 使用 Vite 創建 Vue3 項目
npm create vite@latest my-vue-electron-app -- --template vue
cd my-vue-electron-app
npm install
3.2 安裝 Electron 依賴
# 安裝 Electron(開發依賴)
npm install electron --save-dev
# 安裝 electron-builder(打包工具)
npm install electron-builder --save-dev
3.3 項目結構
my-vue-electron-app/
├── package.json
├── vite.config.js
├── src/ # Vue3 前端代碼
├── main.js # Electron 主進程
├── preload.js # 預加載腳本(安全 IPC 通信)
└── index.html # Electron 渲染進程入口(可選)
4. 配置 Electron 主進程
4.1 創建 main.js(主進程)
在項目根目錄創建 main.js,用於控制 Electron 窗口和 Vue3 應用:
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false, // 禁用 Node.js 集成(安全考慮)
contextIsolation: true, // 啓用上下文隔離
preload: path.join(__dirname, 'preload.js'), // 預加載腳本
},
});
// 開發環境加載 Vite 開發服務器
if (process.env.NODE_ENV === 'development') {
win.loadURL('http://localhost:5173');
win.webContents.openDevTools(); // 打開 DevTools(可選)
} else {
// 生產環境加載打包後的 Vue3 應用
win.loadFile(path.join(__dirname, '../dist/index.html'));
}
}
// Electron 初始化完成後創建窗口
app.whenReady().then(createWindow);
// 所有窗口關閉時退出應用(macOS 除外)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
// macOS 點擊 Dock 圖標時重新創建窗口
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
4.2 創建 preload.js(預加載腳本)
用於安全地暴露 IPC 通信 API 給 Vue3 渲染進程:
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
// 示例:發送消息到主進程
sendMessage: (message) => ipcRenderer.send('message-from-vue', message),
// 示例:接收主進程消息
onMessage: (callback) => ipcRenderer.on('message-from-main', (event, data) => callback(data)),
});
5. 配置 Vue3 與 Electron 通信
5.1 在 Vue3 組件中使用 IPC
在 Vue3 組件(如 src/App.vue)中調用 Electron API:
<template>
<div>
<h1>Vue3 + Electron 桌面應用</h1>
<button @click="sendMessageToElectron">發送消息給 Electron</button>
<div v-if="messageFromElectron">
<p>來自 Electron 的消息: {{ messageFromElectron }}</p>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const messageFromElectron = ref('');
// 發送消息到 Electron 主進程
const sendMessageToElectron = () => {
window.electronAPI.sendMessage('Hello from Vue3!');
};
// 接收來自 Electron 的消息
onMounted(() => {
window.electronAPI.onMessage((data) => {
messageFromElectron.value = data;
});
});
</script>
5.2 在 main.js 中處理 IPC 消息
修改 main.js,讓 Electron 主進程接收並回復 Vue3 的消息:
const { ipcMain } = require('electron');
// 監聽來自 Vue3 的消息
ipcMain.on('message-from-vue', (event, message) => {
console.log('來自 Vue3 的消息:', message);
// 回覆消息給 Vue3
event.sender.send('message-from-main', 'Electron 收到你的消息了!');
});
6. 打包 Vue3 + Electron 應用
6.1 修改 package.json
{
"name": "my-vue-electron-app",
"version": "1.0.0",
"main": "main.js", // Electron 主進程入口
"scripts": {
"dev": "vite", // 啓動 Vue3 開發服務器
"build": "vite build", // 打包 Vue3 前端
"electron:dev": "concurrently \"npm run dev\" \"wait-on http://localhost:5173 && electron .\"", // 開發模式(Vue3 + Electron)
"electron:build": "npm run build && electron-builder" // 打包生產版本
},
"devDependencies": {
"electron": "^28.0.0",
"electron-builder": "^24.0.0",
"concurrently": "^8.0.0",
"wait-on": "^7.0.0"
},
"build": {
"appId": "com.example.vue-electron",
"productName": "Vue3 Electron App",
"win": { "target": "nsis" }, // Windows 安裝包
"mac": { "target": "dmg" }, // macOS 安裝包
"linux": { "target": "AppImage" } // Linux 安裝包
}
}
6.2 運行 & 打包
(1)開發模式(Vue3 + Electron 同時運行)
npm run electron:dev
(2)打包生產版本
npm run electron:build
✅ 輸出:dist/ 文件夾包含 Windows .exe、macOS .dmg、Linux .AppImage 安裝包。
7. 總結
|
步驟
|
説明
|
|
1. 背景 |
Electron = Web 技術(Vue3) + 桌面應用(Chromium + Node.js)
|
|
2. 架構 |
主進程(管理窗口) + 渲染進程(Vue3 UI) |
|
3. 環境 |
|
|
4. 主進程 |
|
|
5. Vue3 通信 |
|
|
6. 打包 |
|
🚀 下一步:嘗試集成 數據庫、文件管理、或調用原生 API!
📚 官方文檔:https://www.electronjs.org/docs
💡 提示:
- 開發時:用
electron:dev同時運行 Vue3 和 Electron。 - 生產時:用
electron:build打包成安裝包。 - 安全:禁用
nodeIntegration,使用preload.js+contextBridge。