1. 程式人生 > >設定 Chrome 遠端除錯埠

設定 Chrome 遠端除錯埠

Visual Studio Code 斷點除錯 Vue

設定 Chrome 遠端除錯埠

首先我們需要在遠端除錯開啟的狀態下啟動 Chrome, 這樣 VS Code 才能 attach 到 Chrome 上:

Windows

右鍵點選 Chrome 的快捷方式圖示,選擇屬性
在目標一欄,最後加上--remote-debugging-port=9222 注意要用空格隔開

macOS

開啟控制檯執行:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

Linux

開啟控制檯執行:

google-chrome --remote-debugging-port=9222

Visual Stuido Code 安裝外掛

點選 Visual Studio Code 左側邊欄的擴充套件按鈕, 然後在搜尋框輸入Debugger for Chrome並安裝外掛,再輸入,安裝完成後點選 reload 重啟 VS Code

新增 Visual Studio Code 配置

點選 Visual Studio Code 左側邊欄的 除錯 按鈕, 在彈出的除錯配置視窗中點選 設定 小齒輪, 然後選擇 chrome, VS Code 將會在工作區根目錄生成.vscode 目錄,裡面會有一個 lanch.json 檔案並會自動開啟
用下面的配置檔案覆蓋自動生成的 lanch.json 檔案內容。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "attach",
      "name": "Attach to Chrome",
      "port": 9222,
      "webRoot": "${workspaceRoot}/src",
      "url": "http://localhost:8080/#/",
      "sourceMaps": true,
      "sourceMapPathOverrides": {
        "webpack:///src/*": "${webRoot}/*"
      }
    }
  ]
}

修改 webpack 的 sourcemap

如果你是基於 webpack 打包的 vue 專案, 可能會存在斷點不匹配的問題, 還需要做些修改:

開啟根目錄下的 config 目錄下的 index.js 檔案
將dev 節點下的 devtool 值改為 ‘eval-source-map’
將dev節點下的 cacheBusting 值改為 false

開始除錯吧

一切具備了, 現在驗收成果了

通過第一步的方式以遠端除錯開啟的方式開啟 Chrome
在 vue 專案中執行npm run dev以除錯方式啟動專案
點選 VS Code 左側邊欄的除錯按鈕,選擇 Attach to Chrome 並點選綠色開始按鈕,正常情況下就會出現除錯控制條。
現在就可以在.vue檔案的js程式碼中打斷點進行除錯了。