Node.js VS Code
用 VS Code 写 Node:调试配置、断点、常用插件。
Key PointsVS Code 自带 Node 调试器,写好 launch.json 就能断点单步,不用装任何插件。
起步
Bash
mkdir demo && cd demo
npm init -y
code .Open a .js file, press F5, and choose Node.js when prompted — VS Code generates .vscode/launch.json for you.
launch.json
JSON
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "启动当前文件",
"program": "${file}",
"skipFiles": ["<node_internals>/**"],
"console": "integratedTerminal"
},
{
"type": "node",
"request": "launch",
"name": "带参数启动",
"program": "${workspaceFolder}/src/index.js",
"args": ["--port", "3000"],
"env": { "NODE_ENV": "development" }
}
]
}| Field | Meaning |
|---|---|
program | 入口文件;${file} 表示当前打开的文件 |
args | 传给 process.argv 的参数 |
env | 环境变量 |
cwd | 工作目录,影响相对路径 |
skipFiles | 单步时跳过哪些文件 |
断点调试
JavaScript
function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2); // 在这里打断点
}
console.log(fib(6));Click left of a line number for a red dot and press F5. Once paused: F10 step over, F11 step into, Shift+F11 step out, hover to inspect values, or evaluate expressions in the DEBUG CONSOLE.
值得装的插件
- ESLint —— 边写边标出问题
- Prettier —— 保存即格式化
- Error Lens —— 错误直接显示在行尾
- npm intellisense —— 补全依赖名
- REST Client ——
.http文件里发请求,替代 Postman
To debug a process started by
npm start, use "request": "launch" with "runtimeExecutable": "npm" and "runtimeArgs": ["start"] — simpler than attaching manually.起步
Bash
mkdir demo && cd demo
npm init -y
code .打开一个 .js 文件,按 F5,VS Code 会让你选环境,选 Node.js 就会自动生成 .vscode/launch.json。
launch.json
JSON
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "启动当前文件",
"program": "${file}",
"skipFiles": ["<node_internals>/**"],
"console": "integratedTerminal"
},
{
"type": "node",
"request": "launch",
"name": "带参数启动",
"program": "${workspaceFolder}/src/index.js",
"args": ["--port", "3000"],
"env": { "NODE_ENV": "development" }
}
]
}| 字段 | 含义 |
|---|---|
program | 入口文件;${file} 表示当前打开的文件 |
args | 传给 process.argv 的参数 |
env | 环境变量 |
cwd | 工作目录,影响相对路径 |
skipFiles | 单步时跳过哪些文件 |
断点调试
JavaScript
function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2); // 在这里打断点
}
console.log(fib(6));在行号左侧点一下出现红点,F5 启动。停下来后可以:F10 单步跳过、F11 单步进入、Shift+F11 跳出、鼠标悬停看变量值、在 DEBUG CONSOLE 里直接执行表达式。
值得装的插件
- ESLint —— 边写边标出问题
- Prettier —— 保存即格式化
- Error Lens —— 错误直接显示在行尾
- npm intellisense —— 补全依赖名
- REST Client ——
.http文件里发请求,替代 Postman
调试
npm start 启动的进程时,用 "request": "launch" + "runtimeExecutable": "npm" + "runtimeArgs": ["start"],比手动 attach 省事。