Node.js VS Code

用 VS Code 写 Node:调试配置、断点、常用插件。

Beginner
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" }
    }
  ]
}
FieldMeaning
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.

Friends & Partners