一般大家調試都是在瀏覽器端調試js的,不過有些時候也想和后台一樣在代碼工具里面調試js或者node.js,下面介紹下怎樣在vscode里面走斷點。
1,用來調試js
一:在左側擴展中搜索Debugger for Chrome並點擊安裝:
二:在自己的html工程目錄下面點擊f5,或者在左側選擇調試按鈕
,在上方
,選擇下拉按鈕,會有一個添加,選擇chrome
3:之后會出現laungh.json的配置文件在自己的項目目錄下面
4:不過對於不同的代碼文件要調試的話,每次都需要修改一下配置文件
{
"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:到這里就可以進行調試了,在
中選擇 Launch index.html (disable sourcemaps) 調試項,按f5調試,會出現,同時打開goole瀏覽器,點擊
,即可進入調試階段
2,用來調試node.js
調試nodejs有很多方式,可以看這一篇 https://blog.risingstack.com/how-to-debug-nodej-js-with-the-best-tools-available/,
其中我最喜歡使用的還是V8 Inspector和vscode的方式。
在vscode中,點擊那個蜘蛛的按鈕
就能看出現debug的側欄,接下來添加配置
選擇環境
就能看到launch.json的文件了。
啟動的時候,選擇相應的配置,然后點擊指向右側的綠色三角
launch模式與attach模式
{
"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
}