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-store
2、主进程 main.js
实例
const { app, BrowserWindow, ipcMain } = require('electron')
const Store = require('electron-store')
const store = new Store()
let mainWindow
app.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))
const Store = require('electron-store')
const store = new Store()
let mainWindow
app.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)
})
contextBridge.exposeInMainWorld('api', {
getNotes: () => ipcRenderer.invoke('get-notes'),
saveNotes: (notes) => ipcRenderer.invoke('save-notes', notes)
})
4、渲染进程 index.html
实例
<!DOCTYPE html>
<html>
<body>
<textarea id="note"></textarea>
<button id="saveBtn">保存</button>
<script>
const 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>
<html>
<body>
<textarea id="note"></textarea>
<button id="saveBtn">保存</button>
<script>
const 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.js
const 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))
const 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)
})
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].path
window.api.moveFile(filePath, targetDir)
})
const dropArea = document.getElementById('fileList')
dropArea.addEventListener('drop', (event) => {
event.preventDefault()
const filePath = event.dataTransfer.files[0].path
window.api.moveFile(filePath, targetDir)
})
性能优化
- 对大目录采用异步读取,避免阻塞渲染进程
- 文件列表虚拟化,减少 DOM 渲染压力
- 对频繁操作使用批量更新或 Web Worker
小结
通过这两个实战项目,你可以掌握:
- 窗口与多进程通信:父子窗口、IPC
- 本地数据存储:electron-store、fs
- 界面与性能优化:虚拟列表、懒加载、异步处理
- 原生功能集成:文件操作、拖拽、菜单和快捷键
这些项目可以作为后续复杂桌面应用开发的基础模板,帮助快速搭建功能齐全的 Electron 应用。
点我分享笔记