Electron 桌面应用开发入门:前端工程师的跨平台利器

分类:前端 | 标签:Electron、桌面应用、electron-vite、IPC、前端工程化

前端技术栈已经能覆盖 Web、小程序、App,而 Electron 让同一套 HTML/CSS/JS 还能跑在 Windows、macOS、Linux 桌面上。无论是内部工具、桌面客户端还是跨平台应用,Electron 都是值得前端工程师掌握的技能。本文从「为什么学」「项目搭建」「主进程与渲染进程」「IPC 通信」到「打包分发」和「实战场景」,带你快速入门。


一、为什么前端工程师要学 Electron?

1.1 技术栈复用

  • 使用 HTML、CSS、JavaScript/TypeScript
  • 可集成 Vue、React、Svelte 等框架
  • 一套代码,多端运行(Web + 桌面)

1.2 典型应用

  • VS Code、Cursor、Slack、Discord、Figma Desktop
  • 企业内部管理系统、数据可视化大屏
  • 本地文件处理、系统托盘、剪贴板等桌面能力

1.3 学习成本低

有前端基础即可上手,主要新增概念:主进程、渲染进程、IPC。


二、项目搭建:electron-vite

2.1 为什么选 electron-vite?

  • 基于 Vite,开发时 HMR 快
  • 内置主进程、渲染进程、预加载脚本的构建配置
  • 支持 Vue、React 等模板

2.2 创建项目

bash 复制代码
npm create @quick-start/electron
# 选择 vue-ts 或 react-ts 等模板

或手动初始化:

bash 复制代码
mkdir my-electron-app && cd my-electron-app
npm init -y
npm install electron electron-vite vite vue -D

2.3 目录结构

perl 复制代码
my-electron-app/
├── src/
│   ├── main/           # 主进程
│   │   └── index.ts
│   ├── preload/        # 预加载脚本
│   │   └── index.ts
│   └── renderer/       # 渲染进程(前端页面)
│       ├── index.html
│       ├── main.ts
│       └── App.vue
├── electron.vite.config.ts
└── package.json

2.4 package.json 关键配置

json 复制代码
{
  "main": "out/main/index.js",
  "scripts": {
    "dev": "electron-vite dev",
    "build": "electron-vite build",
    "preview": "electron-vite preview"
  },
  "devDependencies": {
    "electron": "^28.0.0",
    "electron-vite": "^2.0.0",
    "vite": "^5.0.0"
  }
}

三、主进程 vs 渲染进程

3.1 概念

进程 职责 可访问
主进程 创建窗口、系统 API、原生模块 Node.js、Electron API
渲染进程 展示页面、用户交互 受限的 Node(通过 preload)

3.2 主进程示例:创建窗口

typescript 复制代码
// src/main/index.ts
import { app, BrowserWindow } from 'electron'
import path from 'path'

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

  if (process.env.NODE_ENV === 'development') {
    win.loadURL('http://localhost:5173')
    win.webContents.openDevTools()
  } else {
    win.loadFile(path.join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(createWindow)
app.on('window-all-closed', () => app.quit())

3.3 渲染进程

就是普通的前端页面,用 Vue/React 开发即可,运行在 Chromium 中。


四、IPC 通信

渲染进程不能直接访问 Node 和部分 Electron API,需要通过 预加载脚本 暴露安全接口,再通过 IPC 与主进程通信。

4.1 预加载脚本(Preload)

typescript 复制代码
// src/preload/index.ts
import { contextBridge, ipcRenderer } from 'electron'

contextBridge.exposeInMainWorld('electronAPI', {
  readFile: (path: string) => ipcRenderer.invoke('read-file', path),
  onMessage: (callback: (msg: string) => void) =>
    ipcRenderer.on('message', (_, msg) => callback(msg))
})

4.2 主进程:注册 IPC 处理

typescript 复制代码
// src/main/index.ts
import { ipcMain } from 'electron'
import fs from 'fs/promises'

ipcMain.handle('read-file', async (_, filePath) => {
  return await fs.readFile(filePath, 'utf-8')
})

4.3 渲染进程:调用

typescript 复制代码
// 在 Vue/React 组件中
const content = await window.electronAPI.readFile('/path/to/file.txt')

4.4 类型声明(TypeScript)

typescript 复制代码
// src/renderer/types/electron.d.ts
export interface ElectronAPI {
  readFile: (path: string) => Promise<string>
  onMessage: (callback: (msg: string) => void) => void
}

declare global {
  interface Window {
    electronAPI: ElectronAPI
  }
}

五、打包与分发

5.1 使用 electron-builder

bash 复制代码
npm install electron-builder -D
json 复制代码
// package.json
{
  "build": {
    "appId": "com.example.myapp",
    "productName": "MyApp",
    "directories": {
      "output": "dist"
    },
    "win": {
      "target": "nsis"
    },
    "mac": {
      "target": "dmg",
      "category": "public.app-category.utilities"
    }
  }
}

5.2 打包命令

bash 复制代码
npm run build
npx electron-builder

产物在 dist/ 下,如 Windows 的 .exe 安装包、macOS 的 .dmg


六、实战场景示例

6.1 读取本地文件

主进程用 fs,通过 IPC 暴露给渲染进程(见上文 IPC 示例)。

6.2 系统托盘

typescript 复制代码
// src/main/index.ts
import { Tray } from 'electron'
import path from 'path'

const tray = new Tray(path.join(__dirname, 'icon.png'))
tray.setToolTip('My App')
tray.on('click', () => win.show())

6.3 打开外部链接

typescript 复制代码
import { shell } from 'electron'
shell.openExternal('https://example.com')

6.4 剪贴板

typescript 复制代码
import { clipboard } from 'electron'
clipboard.writeText('Hello')
const text = clipboard.readText()

七、开发建议

  1. 安全 :开启 contextIsolation,关闭 nodeIntegration,通过 preload 暴露最小接口
  2. 性能:避免在主进程做耗时操作,用 Worker 或异步 IPC
  3. 体积:合理使用 asar 打包,排除无用依赖
  4. 更新:可集成 electron-updater 做自动更新

总结

模块 要点
搭建 electron-vite + Vue/React,开发体验好
进程 主进程管窗口和系统,渲染进程管 UI
IPC preload 桥接 + contextBridge 暴露 API
打包 electron-builder 生成 exe/dmg
场景 内部工具、桌面客户端、跨平台应用

掌握 Electron,前端能力边界可以扩展到桌面端,值得花时间实践一个完整项目。


我是前端老兵AI,2016年入行,9年+全场景前端工程师。专注 AI 编程提效 + 前端实战 + 副业变现。

📦 公众号搜索「前端老兵之AI 」→ 后台回复「干货包」 免费领取:Cursor 完整配置模板(Vue3/React/Node 三套)+ AI 工作流手册 + 外包报价表

🎬 B站「前端老兵AI」 每周实操视频,比文章更直观

💬 点赞收藏,下次遇到直接翻出来用!评论区说说你踩过的坑,我会认真回复

相关推荐
科科睡不着2 小时前
拆解iOS实况照片📷 - 附React web实现
前端
胖子不胖2 小时前
浅析cubic-bezier
前端
reasonsummer2 小时前
【办公类-133-02】20260319_学区化展示PPT_02_python(图片合并文件夹、提取同名图片归类文件夹、图片编号、图片GIF)
前端·数据库·powerpoint
胡耀超2 小时前
Web Crawling 网络爬虫全景:技术体系、反爬对抗与全链路成本分析
前端·爬虫·python·网络爬虫·数据采集·逆向工程·反爬虫
阿明的小蝴蝶2 小时前
记一次Gradle环境的编译问题与解决
android·前端·gradle
Ruihong2 小时前
【VuReact】轻松实现 Vue 到 React 路由适配
前端·react.js
山_雨2 小时前
startViewTransition
前端
写代码的【黑咖啡】2 小时前
Python Web 开发新宠:FastAPI 全面指南
前端·python·fastapi
凉_橙2 小时前
gitlab CICD
前端