一直想寫一篇關於 VS Code 的 Debugger for Chrome 的文章,沒想到拖到了今天。VS Code 開源後在社群中獲得了廣泛支持,優點不必多贅述,本文聚焦於 Debugger for Chrome 這個擴充的使用。網路上這方面的好文章不多,於是筆者決定自己整理一篇。
說實話,光看官方那篇文章,很多人對如何上手仍是一知半解,因為它對如何 new instance 與 attach 講得不夠透徹。以下就來梳理這兩種調試方式的要點。
1、首先要有 .vscode/launch.json 檔案,它被放在原始碼資料夾下,其中 .vscode 是目錄,launch.json 是調試設定檔,調試器靠它來 new instance 或 attach。前半段設定用於 new instance,後半段用於 attach:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Chrome and new instance of Chrome",
"type": "chrome",
"request": "launch",
"url": "https://localhost:8080/Test/index.html",
"sourceMaps": true,
"webRoot": "E:/apache-tomcat-8.0.21/webapps/Test"
},
{
"name": "Attach to Chrome",
"type": "chrome",
"request": "attach",
"port": 9222,
"sourceMaps": true,
"webRoot": "${workspaceRoot}"
}
]
}
2、url 方式需要 web server 支援,否則會遇到網路連線問題;而本機 attach 方式則需為 Chrome 加上啟動參數,例如 "--remote-debugging-port=9222"。
3、無論 attach 還是 new chrome instance,都需要透過 webRoot 參數指定原始檔路徑。這一點在體驗上不如直接用瀏覽器調試——後者不需要這個設定就能中斷點,若調試者本身沒有原始碼就更麻煩。
總結
本文分析了 VS Code 的 Debugger for Chrome 兩種調試方式(launch 與 attach)及其要點,並附上實機調試的截圖,希望對大家有所幫助。