HoRain云--Electron 实战项目
通过实战项目可以加深对 Electron 各种特性的理解包括窗口管理、IPC 通信、文件操作、数据存储和界面优化。项目一桌面笔记应用功能设计创建、编辑、删除笔记自动保存与本地存储支持多窗口同时编辑界面简洁提供 Markdown 渲染技术选型前端框架Vue 或 React渲染进程展示笔记内容支持富文本 / Markdown数据存储electron-store保存笔记数据主进程管理窗口、菜单和快捷键IPC 通信渲染进程请求主进程读取或保存数据实现步骤1、创建 Electron 项目mkdir electron-notes cd electron-notes npm init -y npm install electron electron-store2、主进程 main.js实例const { app, BrowserWindow, ipcMain } require(electron)const Store require(electron-store)const store new Store()let mainWindowapp.whenReady().then(() {mainWindow new BrowserWindow({width: 800,height: 600,webPreferences: {preload: ${__dirname}/preload.js}})mainWindow.loadFile(index.html)})// IPC读取笔记ipcMain.handle(get-notes, () store.get(notes, []))// IPC保存笔记ipcMain.handle(save-notes, (event, notes) store.set(notes, notes))3、预加载脚本 preload.js实例const { contextBridge, ipcRenderer } require(electron)contextBridge.exposeInMainWorld(api, {getNotes: () ipcRenderer.invoke(get-notes),saveNotes: (notes) ipcRenderer.invoke(save-notes, notes)})4、渲染进程 index.html实例!DOCTYPE htmlhtmlbodytextarea idnote/textareabutton idsaveBtn保存/buttonscriptconst textarea document.getElementById(note)const btn document.getElementById(saveBtn)window.api.getNotes().then(notes {textarea.value notes.join(\n\n)})btn.addEventListener(click, async () {await window.api.saveNotes([textarea.value])alert(保存成功)})/script/body/html代码解析electron-store负责本地数据存储自动序列化 JSONipcMain.handle/ipcRenderer.invoke实现渲染进程与主进程通信contextBridge安全暴露 API 给渲染进程textarea按钮简单实现笔记内容编辑与保存项目二文件管理器界面设计左侧目录树右侧文件列表支持文件操作新增、删除、重命名拖拽文件到目标目录简单搜索和排序功能文件操作实现Node.js fs 模块读取、写入、删除文件path 模块路径处理IPC 通信渲染进程请求主进程进行文件操作实例// 主进程 main.jsconst fs require(fs)const path require(path)ipcMain.handle(read-dir, (event, dirPath) fs.readdirSync(dirPath))ipcMain.handle(create-file, (event, filePath) fs.writeFileSync(filePath, ))ipcMain.handle(delete-file, (event, filePath) fs.unlinkSync(filePath))实例// 渲染进程window.api.readDir(/Users/username/Documents).then(files {console.log(files)})拖拽功能渲染进程监听dragstart和drop事件主进程使用fs.rename或fs.copyFile移动文件实例// 渲染进程 drop 事件const dropArea document.getElementById(fileList)dropArea.addEventListener(drop, (event) {event.preventDefault()const filePath event.dataTransfer.files[0].pathwindow.api.moveFile(filePath, targetDir)})性能优化对大目录采用异步读取避免阻塞渲染进程文件列表虚拟化减少 DOM 渲染压力对频繁操作使用批量更新或 Web Worker小结通过这两个实战项目你可以掌握窗口与多进程通信父子窗口、IPC本地数据存储electron-store、fs界面与性能优化虚拟列表、懒加载、异步处理原生功能集成文件操作、拖拽、菜单和快捷键这些项目可以作为后续复杂桌面应用开发的基础模板帮助快速搭建功能齐全的 Electron 应用。