Post

Electron 实践

Electron 实践

最近用 Electron 开发了一个桌面应用,并结合 Vue 框架完成了一个小项目。记录一下 Electron 的核心知识,包括基础概念、窗口管理、API 使用、安全性与优化,以及如何将 Vue 项目打包为桌面应用。

一、Electron 基础

什么是 Electron?它的核心作用是什么?

Electron 允许开发者使用 HTML、CSS 和 JavaScript 构建桌面应用,支持 Windows、macOS 和 Linux。

核心作用:

  • 跨平台开发:用 Web 技术创建原生桌面应用,减少跨平台适配成本。
  • 原生能力:通过 Node.js 访问系统资源(如文件系统、通知),提供原生体验。
  • 生态支持:集成 Chromium 引擎,支持现代 Web 技术(如 ES6、CSS3)。

二、窗口管理

BrowserWindow 的常见配置

Electron 使用 BrowserWindow 创建和管理窗口。以下是基本步骤:

创建窗口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// main.js
const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 启用 Node.js 集成
      contextIsolation: false // 关闭上下文隔离
    }
  });

  mainWindow.loadFile('index.html'); // 加载 HTML 文件
  mainWindow.on('closed', () => { mainWindow = null; });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
app.on('activate', () => { if (mainWindow === null) createWindow(); });

常见配置:

  • width/height:窗口尺寸。
  • webPreferences
    • nodeIntegration:允许渲染进程使用 Node.js API。
    • contextIsolation:隔离渲染进程和主进程(安全性)。
  • show:初始是否显示窗口。
  • frame:是否显示窗口边框。
  • resizable:窗口是否可调整大小。

多窗口管理与数据共享

多窗口管理: 通过创建多个 BrowserWindow 实例实现:

1
2
3
4
5
6
7
8
9
10
let secondaryWindow;

function createSecondaryWindow() {
  secondaryWindow = new BrowserWindow({
    width: 400,
    height: 300,
    parent: mainWindow // 设置父窗口
  });
  secondaryWindow.loadFile('secondary.html');
}

数据共享:

  • IPC 通信:使用 ipcMainipcRenderer 在主进程和渲染进程间通信。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    // 主进程 (main.js)
    const { ipcMain } = require('electron');
    ipcMain.on('share-data', (event, data) => {
      secondaryWindow.webContents.send('receive-data', data);
    });
    
    // 渲染进程 (mainWindow)
    const { ipcRenderer } = require('electron');
    ipcRenderer.send('share-data', 'Hello from main window');
    
    // 渲染进程 (secondaryWindow)
    ipcRenderer.on('receive-data', (event, data) => {
      console.log(data); // 输出 'Hello from main window'
    });
    
  • 全局变量:在主进程中使用全局对象(如 global.sharedData)。

三、Electron API

与原生系统交互的 API

Electron 提供了丰富的 API,与原生系统交互:

  • 文件系统:通过 Node.js 的 fs 模块读写文件。
  • 剪贴板(clipboard):读写剪贴板内容。
    1
    2
    
    const { clipboard } = require('electron');
    clipboard.writeText('Hello Electron');
    
  • 通知(Notification):显示桌面通知。
    1
    2
    
    const { Notification } = require('electron');
    new Notification({ title: '提示', body: '任务完成' }).show();
    
  • 系统托盘(Tray):创建任务栏图标。

使用 fs 模块访问本地文件系统

示例: 读取本地文件并显示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 渲染进程
const { ipcRenderer } = require('electron');

// 主进程
const { ipcMain } = require('electron');
const fs = require('fs');

ipcMain.on('read-file', (event) => {
  fs.readFile('data.txt', 'utf8', (err, data) => {
    if (err) throw err;
    event.reply('file-content', data);
  });
});

// 渲染进程
ipcRenderer.send('read-file');
ipcRenderer.on('file-content', (event, data) => {
  console.log(data); // 输出文件内容
});

使用场景: 读取用户配置文件、保存日志等。

四、优化

性能优化

  • 减少内存占用:限制 BrowserWindow 数量,关闭不必要的窗口。
  • 优化打包体积
    • 使用 electron-builderasar 打包,压缩资源。
    • 删除不必要的依赖,压缩 HTML/CSS/JS。

五、打包与发布

这里我是用的脚手架electron-vue,里面自带了electron-builder

配置: 在 package.json 中添加:

1
2
3
4
5
6
7
8
{
  "build": {
    "productName": "MyApp", // 打包应用的名字
    "win": { "target": "nsis" },
    "mac": { "target": "dmg" },
    "files": ["dist_electron/**/*"]
  }
}

打包:

1
node .electron-vue/build.js && electron-builder
This post is licensed under CC BY 4.0 by the author.