如何在 VSCode 中调试 Electron

1 步骤

  • 将 vscode 切换到 debug 视图 ( Ctrl+Shift+D )

  • 打开 launch.json

.在 configurations 节点下添加以下对象并保存

1
2
3
4
5
6
7
8
{
"type": "node",
"request": "launch",
"name": "Electron Main",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"program": "${workspaceRoot}/main.js",
"protocol": "legacy"
}
  • 在 main.js 中添加一个断点

  • 在 vscode 中点击 “开始调试”

,命中断点,即可开始调试。

2 变量

在 launch.json 中有一些预定义的变量:

  • ${workspaceRoot} VSCode 打开的文件夹目录路径

  • ${workspaceRootFolderName} 根路径文件夹名称

  • ${file} 当前打开的文件

  • ${relativeFile} 当前打开文件相对于 workspaceRoot 的相对路径

  • ${fileBasename} 当前打开文件的文件名

  • ${fileBasenameNoExtension} 不带扩展名的文件名

  • ${fileExtname} 当前打开文件的扩展名

  • ${fileDirname} 当前打开文件的文件夹名称

  • ${cwd} 运行任务的工作路径

  • ${lineNumber} 当前文件的选择行

除了这些预定义的变量,还可以使用

  • ${env:Name} 来使用环境变量,如 ${env:PATH}

  • ${config:Name} 来使用 VSCode 的设置,如 ${config:editor.fontSize}

  • ${command:CommandID} 来执行命令行,如 ${command:explorer.newFolder} (windows)

3 不同操作系统的配置

launch.js 还支持对不同的操作系统作特殊配置,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Main Process",
"type": "node",
"request": "launch",
"cwd": "${workspaceRoot}",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
},
"args" : ["."]
}
]
}

对于 runtimeExecutable 节点, windows 操作系统使用 electron.cmd 文件,而其它操作系统使用 electron 操作系统分别定义为: windows , linux , osx 三种。