====== Electron 快速开始 ======
从零跑起一个最小可运行的 Electron 工程。跑通之后再考虑打包与脚手架。
* 返回:[[electron|Electron 知识地图]]
* 前置条件:Node.js 18 以上(建议 20 LTS),''npm'' 可用
===== 一、环境准备 =====
node -v
npm -v
mkdir my-electron-demo
cd my-electron-demo
npm init -y
npm i -D electron@latest
npx electron --version
能打印出版本号,说明 Electron 的二进制已正确下载安装。若卡在下载环节,可先配置镜像再重试。
===== 二、最小工程的四个文件 =====
my-electron-demo/
├─ package.json
├─ main.js 主进程
├─ preload.js 桥接层
├─ index.html 界面
└─ renderer.js 界面脚本
==== package.json ====
关键是 ''main'' 与 ''start'' 两个字段。不要加 type 为 module 的声明,保持 CommonJS 最省事。
{
"name": "my-electron-demo",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^33.0.0"
}
}
==== main.js ====
主进程:创建窗口、注册 IPC 处理函数、管理应用生命周期。安全相关的三个选项保持安全取值。
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')
function createWindow () {
const win = new BrowserWindow({
width: 1000,
height: 700,
show: false,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
})
win.once('ready-to-show', () => win.show()) // 避免白屏闪烁
win.loadFile('index.html')
}
// 最典型的 IPC:渲染进程请求,主进程应答
ipcMain.handle('ping', () => 'pong from main')
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
==== preload.js ====
只通过 ''contextBridge'' 暴露最小粒度的 API,绝不整体暴露 ''ipcRenderer''。
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
ping: () => ipcRenderer.invoke('ping'),
electronVersion: process.versions.electron
})
==== renderer.js ====
这是普通网页脚本,拿不到 ''fs'' 等 Node 模块,需要系统能力时一律走 IPC。
document.getElementById('btn').addEventListener('click', async () => {
const pong = await window.api.ping()
document.getElementById('out').textContent =
`${pong} / Electron ${window.api.electronVersion}`
})
==== index.html ====
用普通脚本标签引入同目录的 renderer.js,并声明一条基础 CSP,禁止内联脚本。
Hello Electron