很多人習慣在 Chrome 的調試窗口中調試 Vue 代碼, 或者直接使用 console.log 來觀察變量值, 這是非常痛苦的一件事,需要同時打開至少 3 個窗體。個人還是更加習慣于斷點調試。這篇文章將介紹如何配置 Visual Studio Code 和 Chrome 來完成直接在 VS Code 斷點調試代碼, 并且在VS Code的調試窗口看到Chrome中console相同的值。
設置 Chrome 遠程調試端口
首先我們需要在遠程調試打開的狀態下啟動 Chrome, 這樣 VS Code 才能 attach 到 Chrome 上:
Windows
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 配置
{ // 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 項目, 可能會存在斷點不匹配的問題, 還需要做些修改:
開始調試吧
一切具備了, 現在驗收成果了
新聞熱點
疑難解答