Chuyển đến nội dung

Bài 19 · Debugging

launch.json: Debug Configurations

Write VS Code launch.json files: launch vs attach, program, args, env, cwd, console, preLaunchTask, skipFiles, variables like workspaceFolder, compound configurations and a runnable validator.

Pressing F5 on a simple file often just works, because VS Code creates a temporary configuration for you. For real projects you describe how to start or attach to a program in a file named .vscode/launch.json. This lesson explains every common field, the variables you can use, and how to run several things at once.

Creating the file

Open Run and Debug (Ctrl+Shift+D) and click create a launch.json file, or run Debug: Add Configuration... from the Command Palette. Pick an environment (Node.js, Python, C#, Java ...). VS Code writes a starter file and offers an Add Configuration button inside the file with templates.

A minimal Node.js example:

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Run sum.js",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/sum.js",
      "console": "integratedTerminal"
    }
  ]
}

The file is JSONC like the settings file, so comments are allowed. All configurations appear in the drop-down at the top of the Run and Debug view; choose one, press F5.

Required fields

Field Meaning
name Label shown in the drop-down and in compounds
type Which debug adapter to use: node, debugpy, java, coreclr, cppdbg, pwa-chrome, ...
request launch starts the program; attach connects to one that is already running

Beyond these three, the other fields depend on the adapter, but many appear everywhere.

Common fields

  • program: the entry file to run, e.g. ${workspaceFolder}/src/index.js.
  • args: array of command-line arguments, e.g. ["--port", "3000"].
  • cwd: working directory for the program (default is the workspace folder).
  • env: environment variables as an object, e.g. { "NODE_ENV": "development" }. envFile loads variables from a file like ${workspaceFolder}/.env.
  • console: where output and input go:
    • internalConsole (Debug Console, no input)
    • integratedTerminal (the VS Code terminal, supports input)
    • externalTerminal (a separate window)
  • stopOnEntry: pause on the first line. Handy for tracing startup.
  • preLaunchTask: the label of a task in tasks.json to run first, e.g. a build step. postDebugTask runs one afterwards.
  • skipFiles: patterns for code to skip while stepping, such as ["<node_internals>/**", "**/node_modules/**"].
  • cwd/runtimeExecutable/runtimeArgs: for Node, run through a tool: "runtimeExecutable": "npm", "runtimeArgs": ["run", "dev"].
  • justMyCode (Python): true skips library code while stepping.
  • serverReadyAction: open a browser when the program prints a "listening on" line.

Variables

Inside launch.json (and tasks.json) you can use predefined variables:

Variable Value
${workspaceFolder} Absolute path of the opened folder
${workspaceFolderBasename} Folder name only
${file} The file open in the active editor
${fileBasename} sum.js
${fileBasenameNoExtension} sum
${fileDirname} Directory of the active file
${relativeFile} Path relative to the workspace
${lineNumber} Current line in the active editor
${selectedText} Currently selected text
${env:NAME} An environment variable
${config:setting.id} A VS Code setting value
${command:id} Result of a command, e.g. a picker
${input:id} An input defined in an inputs section
${pathSeparator} \ or /

${file} makes a single configuration work for whichever file is open: "program": "${file}" means "debug the current file".

Inputs

Ask for a value each time:

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Run with name",
      "type": "node",
      "request": "launch",
      "program": "${file}",
      "args": ["${input:userName}"]
    }
  ],
  "inputs": [
    {
      "id": "userName",
      "type": "promptString",
      "description": "Name to pass to the program",
      "default": "Ada"
    }
  ]
}

Other input types: pickString (with options) and command.

Launch versus attach

Launch starts your program under the debugger. Attach connects to a process that is already running, which is the right choice for servers started by another tool, for containers, or when you must start with special flags.

JSON
{
  "name": "Attach to Node",
  "type": "node",
  "request": "attach",
  "port": 9229,
  "restart": true
}

Start the program with node --inspect app.js (or --inspect-brk to wait for the debugger), then run this configuration. For Docker or a remote machine, also set address, localRoot and remoteRoot. In VS Code's integrated terminal, the JavaScript Debug Terminal (Command Palette: Debug: JavaScript Debug Terminal) auto-attaches to any Node process you start there, which often removes the need for a configuration.

Compound configurations

Run several configurations together, for example a server and a client:

JSON
{
  "version": "0.2.0",
  "configurations": [
    { "name": "API", "type": "node", "request": "launch", "program": "${workspaceFolder}/api/server.js" },
    { "name": "Web", "type": "node", "request": "launch", "program": "${workspaceFolder}/web/dev.js" }
  ],
  "compounds": [
    {
      "name": "API + Web",
      "configurations": ["API", "Web"],
      "stopAll": true
    }
  ]
}

Pick API + Web in the drop-down and both start; with stopAll, stopping one stops both. The Call Stack view groups the sessions.

Workspace-level debug settings

You can put launch inside a .code-workspace file so multi-root workspaces share configurations. User settings can also contain a launch block, which makes a configuration available everywhere.

A stand-in: validating and expanding a configuration

Typos in launch.json fail in annoying ways. This JavaScript stand-in checks the three required fields, expands ${...} variables from a fake context and prints the resulting command, much like the debugger does before it starts. It is a model, not the real implementation.

JS Stand-in: expand variables and validate

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first configuration passes and shows how ${file} and ${fileBasenameNoExtension} expand. The second and third print the mistakes that VS Code would also flag with a squiggle in launch.json.

Troubleshooting

  1. Nothing happens on F5: the drop-down may hold a configuration for another folder or language; select the correct one.
  2. Wrong working directory: set cwd. Relative paths in your program resolve from it.
  3. Breakpoints are gray (unbound): the source files and the running code do not match. For compiled languages (TypeScript, bundlers) enable source maps ("sourceMaps": true, "outFiles": [...]) and make sure the build is up to date, using preLaunchTask.
  4. Program cannot read input: use "console": "integratedTerminal".
  5. Variable shows ${...} literally: the name is wrong; check the table above.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does request set in a debug configuration?

    The request is launch (start the program) or attach (connect to an existing process).
  2. 2. What does ${workspaceFolder} expand to?

    ${workspaceFolder} is the absolute path of the folder opened in VS Code.
  3. 3. Which console value allows the program to read keyboard input in VS Code?

    internalConsole is output only; integratedTerminal runs the program in a real terminal that accepts input.
  4. 4. What does a compound configuration do?

    Compounds list configuration names that are launched together as one debug action.

Summary

  • .vscode/launch.json defines debug configurations with name, type and request.
  • Use program, args, env, cwd, console, preLaunchTask and skipFiles to shape a run.
  • Variables such as ${workspaceFolder} and ${file} keep configurations portable.
  • attach connects to a running process; compounds start several sessions together.
  • Unbound breakpoints usually mean source maps, outFiles or a stale build.

Next: Debugging Node.js and Python

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.