electron:快速开始

快速开始

Electron 用 HTML + CSS + JavaScript 就能写跨平台桌面应用(Windows / macOS / Linux)。它的本质是:主进程(Node.js)负责窗口和系统能力,渲染进程(Chromium 页面)负责界面,两者通过 IPC 通信。

  • 安装 Node.js LTS(建议 18 / 20 及以上),自带 npm;node -v、npm -v 能输出版本即可。
  • 编辑器推荐 VS Code。
  • 国内下载 Electron 二进制较慢时,先设置镜像:
npm config set registry https://registry.npmmirror.com
npm config set electron_mirror https://npmmirror.com/mirrors/electron/

官方脚手架 Electron Forge 会生成完整工程,自带运行和打包脚本。

# 创建项目(默认模板)
npm init electron-app@latest my-app
 
cd my-app
npm start

想要前端框架 / Vite 热更新模板,加一个 template 参数:

npx create-electron-app@latest my-app --template=vite
npm start

生成的目录大致是这样:

my-app/
├── package.json      # main 指向主进程入口,scripts.start 启动应用
├── forge.config.js   # 打包配置(maker)
└── src/
    ├── main.js       # 主进程:创建窗口、生命周期
    ├── preload.js    # 预加载脚本:桥接安全 API
    └── index.html    # 渲染进程页面(界面)

新建目录后三步:

mkdir my-app && cd my-app
npm init -y
npm install --save-dev electron

1. package.json —— 关键是 main 指向主进程、start 用 electron 启动:

{
  "name": "my-app",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "devDependencies": {
    "electron": "^33.0.0"
  }
}

2. main.js —— 主进程入口,只负责开窗口:

const { app, BrowserWindow } = require('electron')
const path = require('node:path')
 
function createWindow () {
  const win = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,   // 默认值,务必保持 true
      nodeIntegration: false    // 页面里不直接用 Node
    }
  })
  win.loadFile('index.html')
  // 调试时可打开开发者工具
  // win.webContents.openDevTools()
}
 
app.whenReady().then(() => {
  createWindow()
  // macOS:点击 Dock 图标且没有窗口时重新创建
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
 
// 除 macOS 外,关闭所有窗口即退出
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

3. preload.js —— 把需要的能力安全地暴露给页面:

const { contextBridge } = require('electron')
 
contextBridge.exposeInMainWorld('versions', {
  node: () => process.versions.node,
  chrome: () => process.versions.chrome,
  electron: () => process.versions.electron
})

4. renderer.js —— 页面脚本,只能用上面暴露的 window.versions:

document.getElementById('ver').textContent =
  `Electron ${versions.electron()} / Chromium ${versions.chrome()} / Node ${versions.node()}`

3. index.html —— 就是一个普通网页:一个标题、一个用来显示版本号的段落。示例核心内容:

<h1>你好,Electron</h1>
<p id="ver"></p>

再在页面末尾用 script 标签引入 ./renderer.js,并在 head 中加一条 CSP meta(例如 default-src 'self')。

最后启动:

npm start

页面里不能直接调 Node,要请主进程代劳,推荐 invoke / handle 这一对。

主进程注册处理函数:

const { ipcMain, dialog } = require('electron')
 
ipcMain.handle('pick-file', async () => {
  const r = await dialog.showOpenDialog({ properties: ['openFile'] })
  return r.canceled ? null : r.filePaths[0]
})

preload 里包一层,暴露给页面:

const { contextBridge, ipcRenderer } = require('electron')
 
contextBridge.exposeInMainWorld('api', {
  pickFile: () => ipcRenderer.invoke('pick-file')
})

页面里调用:

const file = await window.api.pickFile()
console.log('选中文件:', file)
  • 调试渲染进程:win.webContents.openDevTools(),或快捷键 Ctrl+Shift+I。
  • 调试主进程:启动时加 --inspect=5858,再用 VS Code 附加到该端口。
  • 打包(Forge 项目):
npm run make      # 生成安装包,产物在 out/
npm run package   # 只打包成可执行目录,不做安装程序
  • 常用 maker:Windows 用 Squirrel 或 WiX,macOS 用 DMG,Linux 用 deb / rpm。
  • 若项目用的是 electron-builder:npx electron-builder --win --x64,配置写在 package.json 的 build 字段。
  • contextIsolation: true 保持开启,nodeIntegration 保持关闭,sandbox 用默认开启。
  • 只通过 contextBridge 暴露最小、具体的函数,不要直接把 ipcRenderer 或 require 丢给页面。
  • 页面里加 CSP,不要加载来路不明的远程脚本。
  • IPC 处理函数要校验参数,尤其是文件路径和要执行的命令。
现象 原因 / 解决
npm start 报找不到 electron 依赖没装好,重装一次:npm install --save-dev electron
启动后白屏 检查 loadFile 路径和 package.json 的 main 是否指对入口,打开 DevTools 看报错
require is not defined 页面里本来就不该用 Node,改用 preload + IPC 的方式
下载 Electron 卡住或超时 配置 electron_mirror 镜像,或删掉 node_modules 后重装
改了页面不自动刷新 手动 Ctrl+R 刷新,或用 Vite 模板获得热更新
安装包几百 MB 正常,Electron 内置整个 Chromium;可用 asar 打包、裁剪资源来瘦身
  • 需要菜单、托盘、系统通知,看 Menu、Tray、Notification 模块。
  • 需要读写本地文件或 SQLite,放在主进程做,再通过 IPC 暴露。
  • 需要自动更新,用 autoUpdater(Forge 有 update 插件)。
  • 想用 React / Vue,直接用 electron-vite 或 Forge 的 vite 模板起步最省事。

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • electron/快速开始.1793721295.txt.gz
  • 最后更改: 2026/11/03 23:54
  • 由 张叶安