Electron 开发工具
编辑器与插件、DevTools、热重载、调试配置。
Key Points渲染进程用 Chrome DevTools 调,主进程用 --inspect 加 Node 调试器调,两条链路要分开配。
编辑器
| Tool | Why |
|---|---|
| VS Code | 官方推荐,Electron 插件提供主/渲染进程调试模板 |
| WebStorm | 内置 Electron 支持,跳转与重构强 |
| 任何编辑器 | Electron 就是 Node + 浏览器,没有专有格式 |
渲染进程调试
JavaScript
// 开发期自动打开 DevTools
win.webContents.openDevTools({ mode: 'detach' });
// 或运行时用快捷键
// Windows / Linux: Ctrl + Shift + I
// macOS: Cmd + Option + IThe renderer is Chromium, so Elements, Console, Network and Performance all work exactly as when debugging a web page.
主进程调试
Bash
# 启动时打开 Node 调试端口,然后在 VS Code / Chrome 里 attach
electron --inspect=9229 .JSON
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"outputCapture": "std"
}
]
}The main process runs in Node, so browser DevTools cannot see it. Either --inspect and attach a debugger, or use the launch config above and press F5.
热重载
Bash
npm install --save-dev electronmonJSON
{
"scripts": {
"dev": "electronmon ."
}
}Restarting by hand after every main.js edit is tedious. electronmon watches main-process files and restarts automatically; renderer changes only need a window reload.
Tools like
electron-reload must be excluded from production builds. They watch the filesystem, which is useless after packaging, may throw, and slows startup. Isolate them with devDependencies plus an environment check.常用调试技巧
console.log在渲染进程进 DevTools 控制台,在主进程进终端win.webContents.openDevTools()只在开发环境调用process.env.NODE_ENV区分开发与生产,打包时注入
编辑器
| 工具 | 理由 |
|---|---|
| VS Code | 官方推荐,Electron 插件提供主/渲染进程调试模板 |
| WebStorm | 内置 Electron 支持,跳转与重构强 |
| 任何编辑器 | Electron 就是 Node + 浏览器,没有专有格式 |
渲染进程调试
JavaScript
// 开发期自动打开 DevTools
win.webContents.openDevTools({ mode: 'detach' });
// 或运行时用快捷键
// Windows / Linux: Ctrl + Shift + I
// macOS: Cmd + Option + I渲染进程就是 Chromium,DevTools 里的 Elements、Console、Network、Performance 全部可用,和调网页完全一样。
主进程调试
Bash
# 启动时打开 Node 调试端口,然后在 VS Code / Chrome 里 attach
electron --inspect=9229 .JSON
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
},
"args": ["."],
"outputCapture": "std"
}
]
}主进程跑在 Node 里,不能用浏览器的 DevTools。要么 --inspect 加调试器 attach,要么在 VS Code 里配上面这段直接 F5。
热重载
Bash
npm install --save-dev electronmonJSON
{
"scripts": {
"dev": "electronmon ."
}
}改 main.js 后手动重启很烦。electronmon 监听主进程文件变化并自动重启;渲染进程的文件改动直接刷新窗口就够,不需要工具。
electron-reload 这类工具在生产构建里必须排除。它们会监听文件系统,打包后既没用又可能报错,还会拖慢启动。用 devDependencies 加环境判断双重隔离。常用调试技巧
console.log在渲染进程进 DevTools 控制台,在主进程进终端win.webContents.openDevTools()只在开发环境调用process.env.NODE_ENV区分开发与生产,打包时注入