在 VSCode 中使用 JavaScript Debugger

8,052 阅读2分钟

下面以 Vue 项目为例说明

1 安装

目前 Debugger for Chrome 已经处于遗留状态,不建议使用。

建议安装 JavaScript Debugger (Nightly) 。该版本为预览版本,需要将内置版本禁止掉[1]

  1. Open the extensions view (ctrl+shift+x) and search for @builtin @id:ms-vscode.js-debug
  2. Right click on the JavaScript Debugger extension and Disable it.
  3. Search for @id:ms-vscode.js-debug-nightly in the extensions view.
  4. Install that extension.

2 配置

2.1 launch 模式

  1. 首先在项目中新建 launch.json ,使用 launch 模式进行 debugger,新建如下所示配置
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-chrome",
      "request": "launch",
      "name": "launch vuejs: chrome",
      "url": "https://localhost:8080/",
      "webRoot": "${workspaceFolder}/src",
      "breakOnLoad": true,
      "sourceMaps": true,
      "sourceMapPathOverrides": {
        "webpack:///src/*": "${webRoot}/*"
      }
    }
  ]
}
  1. 找到 “运行与调试” 菜单,找到启动按钮(vscode 顶部绿色按钮);
  2. 在代码行数处,设置断点,即可进行调试;

上述方式中,需要清楚一下几点:

  1. url 为你本地需要进行调试的项目地址。
  2. "sourceMaps": true, 开启源码映射功能,从而更好的调试源码;
  3. 设置源码映射路径 sourceMapPathOverrides ,上面映射了 webpack 打包后的源码文件夹到项目的 src 目录;其他需要映射的目录,可以自行添加。

2.2 attach 模式

launch 模式,会打开新的的 Chrome 窗口,该窗口,不能使用浏览器的其他插件,如 vue devtool。

而使用 attach 模式,可以正常使用浏览器插件,具体配置流程如下:

  1. 首先先关闭所有的Chrome窗口(确保任务管理器中Chrome进程都被关闭掉了!)[2]
  2. 找到Chrome启动快捷键,右键打开属性,在“目标”中增加启动参数--remote-debugging-port=9222 ,记住这里的端口为 9222 后面会用到;大致如下:
    "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
    
  3. 配置你的 launch.json,注意 port 要和前面配置的 9222 一致例如:
{
  "configurations": [
    {
      "type": "chrome",
      "request": "attach",
      "name": "attach vuejs: chrome",
      "urlFilter": "https://localhost:8083/*",
      "port": 9222,
      "webRoot": "${workspaceFolder}/src",
      "breakOnLoad": true,
      "sourceMaps": true,
      "sourceMapPathOverrides": {
        "webpack:///src/*": "${webRoot}/*"
      }
    }
  ]
}
  1. 启动你的本地项目,在Chrome中打开项目地址,如 http://localhost:8080
  2. 在VSCode中运行'Start debugging',启动调试;

2.2.1 遇到的问题

(1) could not connect https://localhost:8083

出现这种情况,本人刚开始在 attach 模式中,配置了 "url": "https://localhost:8083/" 。这种URL配置不适用于 attach 模式。换成 "urlFilter": "https://localhost:8083/*" ,并使用通配符,只响应该地址下的页面。

[1] marketplace.visualstudio.com/items?itemN…;

[2] newbedev.com/cannot-debu…