通常你們調試都是在瀏覽器端調試js的,不過有些時候也想和後臺同樣在代碼工具裏面調試js或者node.js,下面介紹下怎樣在vscode裏面走斷點。html
一:在左側擴展中搜索Debugger for Chrome並點擊安裝: node
二:在本身的html工程目錄下面點擊f5,或者在左側選擇調試按鈕 web
{
"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:到這裏就能夠進行調試了,在 chrome
調試nodejs有不少方式,能夠看這一篇 blog.risingstack.com/how-to-debu…npm
其中我最喜歡使用的仍是V8 Inspector和vscode的方式。 在vscode中,點擊那個蜘蛛的按鈕 json
{
"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更方便一點。瀏覽器
不少時候咱們將很長的啓動命令及配置寫在了package.json的scripts中,好比bash
"scripts": {
"start": "NODE_ENV=production PORT=8080 babel-node ./bin/www",
"dev": "nodemon --inspect --exec babel-node --presets env ./bin/www"
},
複製代碼
咱們但願讓vscode使用npm的方式啓動並調試,這就須要以下的配置babel
{
"name": "Launch via NPM",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script", "dev" //這裏的dev就對應package.json中的scripts中的dev
],
"port": 9229 //這個端口是調試的端口,不是項目啓動的端口
},
複製代碼
僅僅使用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
}
複製代碼