本文摘自PHP中文网,作者藏色散人,侵删。

vscode npm怎么执行?
vscode 调试node之npm与nodemon
调试nodejs有很多方式,可以看这一篇How to Debug Node.js with the Best Tools Available,其中我最喜欢使用的还是V8 Inspector和vscode的方式。
在vscode中,点击那个蜘蛛的按钮
就能看出现debug的侧栏,接下来添加配置
选择环境
就能看到launch.json的文件了。
启动的时候,选择相应的配置,然后点击指向右侧的绿色三角
launch模式与attach模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | {
"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中,比如
1 2 3 4 | "scripts" : {
"start" : "NODE_ENV=production PORT=8080 babel-node ./bin/www" ,
"dev" : "nodemon --inspect --exec babel-node --presets env ./bin/www"
},
|
我们希望让vscode使用npm的方式启动并调试,这就需要如下的配置
1 2 3 4 5 6 7 8 9 10 | {
"name" : "Launch via NPM" ,
"type" : "node" ,
"request" : "launch" ,
"runtimeExecutable" : "npm" ,
"runtimeArgs" : [
"run-script" , "dev"
],
"port" : 9229
},
|
在debug中使用nodemon启动
仅仅使用npm启动,虽然在dev命令中使用了nodemon,程序也可以正常的重启,可重启了之后,调试就断开了。所以需要让vscode去使用nodemon启动项目。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | {
"type" : "node" ,
"request" : "launch" ,
"name" : "nodemon" ,
"runtimeExecutable" : "nodemon" ,
"args" : [ "${workspaceRoot}/bin/www" ],
"restart" : true,
"protocol" : "inspector" ,
"sourceMaps" : true,
"console" : "integratedTerminal" ,
"internalConsoleOptions" : "neverOpen" ,
"runtimeArgs" : [
"--exec" ,
"babel-node" ,
"--presets" ,
"env"
]
},
|
注意这里的runtimeArgs,如果这些配置是写在package.json中的话,就是这样的
1 | nodemon --inspect -- exec babel-node --presets env ./bin/www
|
这样就很方便了,项目可以正常的重启,每次重启一样会开启调试功能。
可是,我们并不想时刻开启调试功能怎么办?
这就需要使用上面说的attach模式了。
使用如下的命令正常的启动项目
1 | nodemon --inspect -- exec babel-node --presets env ./bin/www
|
当我们想要调试的时候,在vscode的debug中运行如下的配置
1 2 3 4 5 6 7 | {
"type" : "node" ,
"request" : "attach" ,
"name" : "Attach to node" ,
"restart" : true,
"port" : 9229
}
|
完美!
以上就是vscode npm怎么执行的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
vsCode中配置和使用java的方法
vsCode无法安装插件怎么办
vsCode格式化代码快捷键是什么
vsCode改不了字体怎么办
web开发中实用的22个vsCode插件
vsCode如何通过文件名查找文件
vsCode如何设置中文语言版本
vsCode中文配置步骤
vsCode无法连接本机mssql怎么办
npm路径怎么添加到vsCode
更多相关阅读请进入《vsCode》频道 >>
转载请注明出处:木庄网络博客 » vscode npm怎么执行