VSCode 使用内置 debug 工具调试 Electron 应用

要在 Visual Studio Code 中配置使用 yarn dev 命令来启动和调试 Electron 应用程序,可以按照以下步骤来设置 launch.json 文件:

  1. 创建或打开 launch.json 文件:
    在 VS Code 中,打开命令面板(Ctrl+Shift+P 或 Cmd+Shift+P),然后输入并选择“调试:打开 launch.json”命令。如果没有现有的 launch.json 文件,VS Code 会为你创建一个。

  2. 添加新的调试配置:
    launch.json 文件中,添加一个新的配置项,用于运行 yarn dev 命令。

下面是一个示例配置,展示如何使用 yarn dev 命令启动和调试 Electron 应用程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Electron with Yarn",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "yarn",
"args": ["dev"],
"windows": {
"runtimeExecutable": "yarn.cmd"
},
"outputCapture": "std",
"env": {
"ELECTRON_ENABLE_LOGGING": "true",
"ELECTRON_ENABLE_STACK_DUMPING": "true"
}
}
]
}

解释配置项

  • name: 调试配置的名称,这里命名为 Debug Electron with Yarn
  • type: 调试类型,设置为 node,用于调试 Node.js 应用。
  • request: 调试请求类型,launch 表示启动一个新的进程进行调试。
  • cwd: 当前工作目录,设置为工作区文件夹。
  • runtimeExecutable: 可执行文件的路径,这里指定为 yarn,在 Windows 上指定为 yarn.cmd
  • args: 传递给 yarn 的参数,这里是 dev,即运行 yarn dev
  • outputCapture: 指定输出捕获方式,这里设置为 std,以捕获标准输出和标准错误。
  • env: 环境变量设置,用于启用 Electron 的日志记录和堆栈转储功能,便于调试。

如何使用这个配置

  1. 保存 launch.json 文件。
  2. 打开调试视图(在左侧活动栏中点击带有错误标志的图标)。
  3. 在调试配置下拉菜单中选择 Debug Electron with Yarn
  4. 点击绿色的启动按钮,VS Code 会运行 yarn dev 命令并启动调试会话。

通过这种方式,你可以在 VS Code 中使用 yarn dev 命令启动并调试你的 Electron 应用程序。