一般大家除錯都是在瀏覽器端除錯js的,不過有些時候也想和後臺一樣在程式碼工具裡面除錯js或者node.js,下面介紹下怎樣在vscode裡面走斷點。
1,用來除錯js
一:在左側擴充套件中搜尋Debugger for Chrome並點選安裝:

二:在自己的html工程目錄下面點選f5,或者在左側選擇除錯按鈕




{
"version": "0.2.0",
"configurations": [{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceRoot}"
},
{
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9222,
"webRoot": "${workspaceRoot}"
},
{
"name": "Launch index.html (disable sourcemaps)",
"type": "chrome",
"request": "launch",
"sourceMaps": false,
"file": "${workspaceRoot}/jsTest/test1/test1.html" #每次需要修改這裡的檔案地址
}
]
}
複製程式碼
5:到這裡就可以進行除錯了,在


2,用來除錯node.js
除錯nodejs有很多方式,可以看這一篇 blog.risingstack.com/how-to-debu…
其中我最喜歡使用的還是V8 Inspector和vscode的方式。 在vscode中,點選那個蜘蛛的按鈕





{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceRoot}/index.js"
},
{
"type": "node",
"request": "attach",
"name": "Attach to Port",
"address": "localhost",
"port": 5858
}
]
}
複製程式碼
當request為launch時,就是launch模式了,這是程式是從vscode這裡啟動的,如果是在除錯那將一直處於除錯的模式。而attach模式,是連線已經啟動的服務。比如你已經在外面將專案啟動,突然需要除錯,不需要關掉已經啟動的專案再去vscode中重新啟動,只要以attach的模式啟動,vscode可以連線到已經啟動的服務。當除錯結束了,斷開連線就好,明顯比launch更方便一點。
在debug中使用npm啟動
很多時候我們將很長的啟動命令及配置寫在了package.json的scripts中,比如
"scripts": {
"start": "NODE_ENV=production PORT=8080 babel-node ./bin/www",
"dev": "nodemon --inspect --exec babel-node --presets env ./bin/www"
},
複製程式碼
我們希望讓vscode使用npm的方式啟動並除錯,這就需要如下的配置
{
"name": "Launch via NPM",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script", "dev" //這裡的dev就對應package.json中的scripts中的dev
],
"port": 9229 //這個埠是除錯的埠,不是專案啟動的埠
},
複製程式碼
在debug中使用nodemon啟動
僅僅使用npm啟動,雖然在dev命令中使用了nodemon,程式也可以正常的重啟,可重啟了之後,除錯就斷開了。所以需要讓vscode去使用nodemon啟動專案。
{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "nodemon",
"args": ["${workspaceRoot}/bin/www"],
"restart": true,
"protocol": "inspector", //相當於--inspect了
"sourceMaps": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"runtimeArgs": [ //對應nodemon --inspect之後除了啟動檔案之外的其他配置
"--exec",
"babel-node",
"--presets",
"env"
]
},
複製程式碼
注意這裡的runtimeArgs,如果這些配置是寫在package.json中的話,就是這樣的
nodemon --inspect --exec babel-node --presets env ./bin/www
複製程式碼
這樣就很方便了,專案可以正常的重啟,每次重啟一樣會開啟除錯功能。
可是,我們並不想時刻開啟除錯功能怎麼辦? 這就需要使用上面說的attach模式了。 使用如下的命令正常的啟動專案
nodemon --inspect --exec babel-node --presets env ./bin/www
複製程式碼
當我們想要除錯的時候,在vscode的debug中執行如下的配置
{
"type": "node",
"request": "attach",
"name": "Attach to node",
"restart": true,
"port": 9229
}
複製程式碼