Electron 开发工具

编辑器与插件、DevTools、热重载、调试配置。

Beginner
Key Points渲染进程用 Chrome DevTools 调,主进程用 --inspect 加 Node 调试器调,两条链路要分开配。

编辑器

ToolWhy
VS Code官方推荐,Electron 插件提供主/渲染进程调试模板
WebStorm内置 Electron 支持,跳转与重构强
任何编辑器Electron 就是 Node + 浏览器,没有专有格式

渲染进程调试

JavaScript
// 开发期自动打开 DevTools
win.webContents.openDevTools({ mode: 'detach' });

// 或运行时用快捷键
// Windows / Linux: Ctrl + Shift + I
// macOS:           Cmd + Option + I

The 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 electronmon
JSON
{
  "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 区分开发与生产,打包时注入

Friends & Partners