相当于直接使用 node 命令,用npm run script 脚本
来启动 Node.js 程序是更为常见的场景,比如当目标是运行一个应用。
假设项目的 package.json 有一个用来调试的debug
脚本:
"scripts": {
"debug": "node app.js" // app.js 是启动项目的文件
},
我们要怎么启动项目的跟踪调试呢?
文档指路 ➡️ 【Node.js 调试入门】、【VSCode 中的 Node.js 调试】、【Launch 对 npm 及其他工具的配置支持】
VS Code 支持两种核心调试模式 Launch 和 Attach,Launch 方式是直接以 debug 模式启动应用,并为我们自动添加一个调试器;而 Attach 方式则是将 VSCode 调试器连接到已经运行中的应用程序或进程。我们这里用的是 Launch 方式。
1. 创建 launch.json 配置文件
在终端运行:
cd 当前项目根目录
mkdir .vscode
cd .vscode
touch launch.json
或点击VSCode 的小甲虫图标:


上面蓝色位置圈错了,应该是第一个 Node.js。

2. 修改 launch.json 配置
VSCode 十分智能,预设了很多针对不同需求的启动配置:



让我们来做进一步的修改:
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node", // 调试器类型,我们是 Node.js 环境
"request": "launch", // 请求方式,有 launch(启动) 和 attach(附加) 两种
"name": "Launch via NPM", // 启动配置名称
"runtimeExecutable": "npm", // 任务运行工具,'npm', 'mocha', 'gulp' 等
"runtimeArgs": ["run-script", "debug"], // 传递给执行工具的可选参数
"port": 9339, // 启动程序的端口
"skipFiles": ["<node_internals>/**/*.js"], // 跳过所有 Node.js 的内置模块
"console": "externalTerminal" // 指定启动控制器为外部终端
}
]
}
之前那个启动配置项可以删除,留下这个需要的即可。
我们将 console 属性 设置为外部终端,我们启动调试时 VScode 就会自动打开下图中对应的终端(根据操作系统)。可以根据个人使用习惯,自定义用什么终端 (比如我在 VSCode 设置的 Terminal › External: Osx Exec,从默认的改为了 iTerm2)。

3. 在需要的位置设置断点,启动服务

别忘了先把我们的脚本加上端口
"scripts": {
"debug": "node --inspect-brk=9339 app.js" // 假设 app.js 是启动项目的文件
},


网友评论