banner



How To Add A Breakpoint In Visual Studio

Debugging

Ane of the key features of Visual Studio Lawmaking is its not bad debugging support. VS Code's congenital-in debugger helps advance your edit, compile, and debug loop.

Debugging diagram

Debugger extensions

VS Code has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, or any other language that gets transpiled to JavaScript.

For debugging other languages and runtimes (including PHP, Cherry-red, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Lawmaking Market place or select Install Additional Debuggers in the top-level Run menu.

Below are several popular extensions which include debugging support:

Tip: The extensions shown above are dynamically queried. Select an extension tile above to read the description and reviews to decide which extension is all-time for you.

Beginning debugging

The post-obit documentation is based on the built-in Node.js debugger, but nigh of the concepts and features are applicable to other debuggers besides.

It is helpful to first create a sample Node.js application before reading about debugging. Y'all can follow the Node.js walkthrough to install Node.js and create a simple "Hello Earth" JavaScript application (app.js). One time you lot accept a uncomplicated awarding prepare, this folio will take yous through VS Lawmaking debugging features.

Run and Debug view

To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. Y'all can also use the keyboard shortcut ⇧⌘D (Windows, Linux Ctrl+Shift+D).

Run and Debug icon

The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.

If running and debugging is not yet configured (no launch.json has been created), VS Code shows the Run start view.

Simplified initial Run and Debug view

The top-level Run card has the well-nigh mutual run and debug commands:

Run menu

Launch configurations

To run or debug a simple app in VS Code, select Run and Debug on the Debug beginning view or press F5 and VS Code volition try to run your currently active file.

Notwithstanding, for most debugging scenarios, creating a launch configuration file is beneficial because it allows you to configure and save debugging setup details. VS Code keeps debugging configuration data in a launch.json file located in a .vscode folder in your workspace (project root folder) or in your user settings or workspace settings.

To create a launch.json file, click the create a launch.json file link in the Run showtime view.

launch configuration

VS Lawmaking volition try to automatically detect your debug environment, just if this fails, you will have to choose information technology manually:

debug environment selector

Here is the launch configuration generated for Node.js debugging:

                      {                                    "version"            :                        "0.ii.0"            ,                                    "configurations"            : [                          {                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "name"            :                        "Launch Program"            ,                                    "skipFiles"            : [            "<node_internals>/**"            ],                                    "program"            :                        "${workspaceFolder}            \\            app.js"                          }                          ]            }                  

If you lot get dorsum to the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+East)), you'll come across that VS Code has created a .vscode folder and added the launch.json file to your workspace.

launch.json in Explorer

Note: You tin debug a unproblematic application even if you don't have a binder open up in VS Lawmaking, just information technology is not possible to manage launch configurations and set upward advanced debugging. The VS Code Status Bar is purple if yous do not have a folder open.

Note that the attributes available in launch configurations vary from debugger to debugger. You lot can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space)) to find out which attributes exist for a specific debugger. Hover help is too available for all attributes.

Practice not assume that an attribute that is available for i debugger automatically works for other debuggers too. If yous see green squiggles in your launch configuration, hover over them to larn what the trouble is and try to set them earlier launching a debug session.

launch.json IntelliSense

Review all automatically generated values and make sure that they make sense for your projection and debugging environment.

Launch versus attach configurations

In VS Code, in that location are two cadre debugging modes, Launch and Attach, which handle ii different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your projection.

If you lot come from a browser Programmer Tools background, y'all might not be used to "launching from your tool," since your browser case is already open. When you lot open DevTools, you are simply attaching DevTools to your open browser tab. On the other mitt, if y'all come from a server or desktop background, information technology's quite normal to have your editor launch your process for you, and your editor automatically attaches its debugger to the newly launched process.

The best way to explain the difference between launch and attach is to think of a launch configuration as a recipe for how to start your app in debug way before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code'south debugger to an app or procedure that'southward already running.

VS Lawmaking debuggers typically back up launching a program in debug manner or attaching to an already running program in debug manner. Depending on the request (adhere or launch), different attributes are required, and VS Code's launch.json validation and suggestions should help with that.

Add a new configuration

To add a new configuration to an existing launch.json, use one of the following techniques:

  • Use IntelliSense if your cursor is located inside the configurations array.
  • Press the Add Configuration button to invoke snippet IntelliSense at the start of the array.
  • Choose Add Configuration option in the Run menu.

launch json suggestions

VS Lawmaking too supports compound launch configurations for starting multiple configurations at the same time; for more than details, please read this section.

In order to start a debug session, first select the configuration named Launch Plan using the Configuration dropdown in the Run and Debug view. Once you have your launch configuration ready, showtime your debug session with F5 .

Alternatively, you can run your configuration through the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P)) by filtering on Debug: Select and Start Debugging or typing 'debug ' and selecting the configuration you desire to debug.

As presently every bit a debugging session starts, the DEBUG Console panel is displayed and shows debugging output, and the Condition Bar changes color (orangish for default color themes):

debug session

In addition, the debug status appears in the Condition Bar showing the active debug configuration. Past selecting the debug status, a user tin can alter the active launch configuration and offset debugging without needing to open up the Run and Debug view.

Debug status

Debug actions

One time a debug session starts, the Debug toolbar volition appear on the meridian of the editor.

Debug Actions

  • Continue / Pause F5
  • Footstep Over F10
  • Pace Into F11
  • Step Out ⇧F11 (Windows, Linux Shift+F11)
  • Restart ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)
  • Finish ⇧F5 (Windows, Linux Shift+F5)

Tip: Use the setting debug.toolBarLocation to command the location of the debug toolbar. Information technology can be the default floating, docked to the Run and Debug view, or hidden. A floating debug toolbar tin exist dragged horizontally and also downwards to the editor area.

Run mode

In improver to debugging a plan, VS Code supports running the program. The Debug: Run (Start Without Debugging) action is triggered with ⌃F5 (Windows, Linux Ctrl+F5) and uses the currently selected launch configuration. Many of the launch configuration attributes are supported in 'Run' fashion. VS Code maintains a debug session while the program is running, and pressing the Stop push terminates the program.

Tip: The Run action is ever available, merely not all debugger extensions support 'Run'. In this example, 'Run' volition be the same as 'Debug'.

Breakpoints

Breakpoints tin can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint command (enable/disable/reapply) can be washed in the Run and Debug view'southward BREAKPOINTS section.

  • Breakpoints in the editor margin are normally shown as red filled circles.
  • Disabled breakpoints accept a filled grey circle.
  • When a debugging session starts, breakpoints that cannot be registered with the debugger alter to a gray hollow circle. The same might happen if the source is edited while a debug session without live-edit support is running.

If the debugger supports breaking on different kinds of errors or exceptions, those will besides be bachelor in the BREAKPOINTS view.

The Reapply All Breakpoints command sets all breakpoints once again to their original location. This is helpful if your debug environment is "lazy" and "misplaces" breakpoints in source code that has not nevertheless been executed.

Breakpoints

Optionally, breakpoints tin be shown in the editor'south overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler:

breakpoints in overview ruler

Logpoints

A Logpoint is a variant of a breakpoint that does not "break" into the debugger but instead logs a bulletin to the console. Logpoints are peculiarly useful for injecting logging while debugging product servers that cannot be paused or stopped.

A Logpoint is represented past a "diamond" shaped icon. Log messages are plain text but tin can include expressions to be evaluated inside curly braces ('{}').

Logpoints

Just similar regular breakpoints, Logpoints can be enabled or disabled and can also exist controlled past a condition and/or hit count.

Annotation: Logpoints are supported by VS Code's built-in Node.js debugger, but tin be implemented by other debug extensions. The Python and Coffee extensions, for example, back up Logpoints.

Information inspection

Variables tin exist inspected in the VARIABLES section of the Run and Debug view or by hovering over their source in the editor. Variable values and expression evaluation are relative to the selected stack frame in the Telephone call STACK department.

Debug Variables

Variable values can be modified with the Prepare Value action from the variable'south context menu. Additionally, you can use the Re-create Value activeness to copy the variable's value, or Re-create as Expression activity to copy an expression to access the variable.

Variables and expressions can also be evaluated and watched in the Run and Debug view's Picket section.

Debug Watch

Variable names and values can be filtered by typing while the focus is on the VARIABLES department.

Filtering in the Variables section

Launch.json attributes

There are many launch.json attributes to help back up dissimilar debuggers and debugging scenarios. Equally mentioned in a higher place, you can utilise IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space)) to see the list of bachelor attributes once y'all have specified a value for the blazon attribute.

launch json suggestions

The following attributes are mandatory for every launch configuration:

  • type - the type of debugger to use for this launch configuration. Every installed debug extension introduces a type: node for the built-in Node debugger, for example, or php and get for the PHP and Go extensions.
  • request - the request type of this launch configuration. Currently, launch and adhere are supported.
  • name - the reader-friendly name to appear in the Debug launch configuration dropdown.

Hither are some optional attributes available to all launch configurations:

  • presentation - using the order, group, and hidden attributes in the presentation object, you can sort, group, and hide configurations and compounds in the Debug configuration dropdown and in the Debug quick pick.
  • preLaunchTask - to launch a task before the start of a debug session, set this attribute to the label of a chore specified in tasks.json (in the workspace'southward .vscode folder). Or, this can exist set to ${defaultBuildTask} to use your default build chore.
  • postDebugTask - to launch a job at the very end of a debug session, set this attribute to the proper name of a task specified in tasks.json (in the workspace's .vscode folder).
  • internalConsoleOptions - this aspect controls the visibility of the Debug Console panel during a debugging session.
  • debugServer - for debug extension authors only: this attribute allows y'all to connect to a specified port instead of launching the debug adapter.
  • serverReadyAction - if you desire to open a URL in a web browser whenever the program under debugging outputs a specific bulletin to the debug panel or integrated terminal. For details run into section Automatically open up a URI when debugging a server programme below.

Many debuggers back up some of the following attributes:

  • programme - executable or file to run when launching the debugger
  • args - arguments passed to the program to debug
  • env - environment variables (the value nil can be used to "undefine" a variable)
  • envFile - path to dotenv file with environment variables
  • cwd - current working directory for finding dependencies and other files
  • port - port when attaching to a running process
  • stopOnEntry - pause immediately when the program launches
  • console - what kind of panel to employ, for example, internalConsole, integratedTerminal, or externalTerminal

Variable substitution

VS Code makes commonly used paths and other values available equally variables and supports variable substitution within strings in launch.json. This means that you lot do not take to use absolute paths in debug configurations. For example, ${workspaceFolder} gives the root path of a workspace folder, ${file} the file open in the agile editor, and ${env:Proper name} the environs variable 'Name'. You tin can meet a total list of predefined variables in the Variables Reference or past invoking IntelliSense inside the launch.json string attributes.

                      {                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "proper noun"            :                        "Launch Program"            ,                                    "program"            :                        "${workspaceFolder}/app.js"            ,                                    "cwd"            :                        "${workspaceFolder}"            ,                                    "args"            : [            "${env:USERNAME}"            ]            }                  

Platform-specific properties

Launch.json supports defining values (for example, arguments to be passed to the program) that depend on the operating system where the debugger is running. To do so, put a platform-specific literal into the launch.json file and specify the corresponding properties inside that literal.

Below is an example that passes "args" to the program differently on Windows:

                      {                                    "version"            :                        "0.2.0"            ,                                    "configurations"            : [                          {                                    "type"            :                        "node"            ,                                    "asking"            :                        "launch"            ,                                    "name"            :                        "Launch Programme"            ,                                    "plan"            :                        "${workspaceFolder}/node_modules/gulp/bin/gulpfile.js"            ,                                    "args"            : [            "myFolder/path/app.js"            ],                                    "windows"            : {                                    "args"            : [            "myFolder            \\            path            \\            app.js"            ]                          }                          }                          ]            }                  

Valid operating properties are "windows" for Windows, "linux" for Linux, and "osx" for macOS. Backdrop defined in an operating organisation specific telescopic override properties defined in the global scope.

Delight note that the blazon belongings cannot exist placed inside a platform-specific section, because type indirectly determines the platform in remote debugging scenarios, and that would result in a cyclic dependency.

In the example below, debugging the plan ever stops on entry except on macOS:

                      {                                    "version"            :                        "0.ii.0"            ,                                    "configurations"            : [                          {                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "name"            :                        "Launch Plan"            ,                                    "program"            :                        "${workspaceFolder}/node_modules/gulp/bin/gulpfile.js"            ,                                    "stopOnEntry"            :                        truthful            ,                                    "osx"            : {                                    "stopOnEntry"            :                        faux                          }                          }                          ]            }                  

Global launch configuration

VS Code supports adding a "launch" object inside your User settings. This "launch" configuration will then be shared across your workspaces. For example:

                      "launch"            : {                                    "version"            :                        "0.ii.0"            ,                                    "configurations"            : [{                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "name"            :                        "Launch Program"            ,                                    "programme"            :                        "${file}"                          }]            }                  

Advanced breakpoint topics

Conditional breakpoints

A powerful VS Code debugging feature is the ability to prepare atmospheric condition based on expressions, hit counts, or a combination of both.

  • Expression condition: The breakpoint will exist hit whenever the expression evaluates to true.
  • Hit count: The 'striking count' controls how many times a breakpoint needs to be hit before it will 'interruption' execution. Whether a 'hit count' is respected and the exact syntax of the expression vary amongst debugger extensions.

Yous can add a condition and/or striking count when creating a source breakpoint (with the Add Conditional Breakpoint action) or when modifying an existing one (with the Edit Condition action). In both cases, an inline text box with a dropdown menu opens where you can enter expressions:

HitCount

Condition and hit count editing support is besides supported for office and exception breakpoints. You can initiate condition editing from the context carte or the new inline Edit Condition activity.

An example of condition editing in the BREAKPOINTS view: condition editing in breakpoint view

If a debugger does non support conditional breakpoints, the Add Conditional Breakpoint and Edit Condition actions will be missing.

Inline breakpoints

Inline breakpoints will only be hit when the execution reaches the cavalcade associated with the inline breakpoint. This is particularly useful when debugging minified code which contains multiple statements in a single line.

An inline breakpoint can be set using ⇧F9 (Windows, Linux Shift+F9) or through the context menu during a debug session. Inline breakpoints are shown inline in the editor.

Inline breakpoints tin also have conditions. Editing multiple breakpoints on a line is possible through the context carte du jour in the editor'south left margin.

Part breakpoints

Instead of placing breakpoints directly in source lawmaking, a debugger can back up creating breakpoints by specifying a function name. This is useful in situations where source is not available simply a role name is known.

A function breakpoint is created by pressing the + button in the BREAKPOINTS section header and entering the function name. Function breakpoints are shown with a red triangle in the BREAKPOINTS section.

Data breakpoints

If a debugger supports data breakpoints, they can be set from the VARIABLES view and will become hitting when the value of the underlying variable changes. Data breakpoints are shown with a cerise hexagon in the BREAKPOINTS section.

Debug Console REPL

Expressions can be evaluated with the Debug Panel REPL (Read-Eval-Print Loop) characteristic. To open the Debug Console, utilize the Debug Console action at the superlative of the Debug pane or employ the View: Debug Panel command ( ⇧⌘Y (Windows, Linux Ctrl+Shift+Y)). Expressions are evaluated later you press Enter and the Debug Console REPL shows suggestions as y'all type. If you lot need to enter multiple lines, use Shift+Enter between the lines and then send all lines for evaluation with Enter. Debug Console input uses the mode of the active editor, which means that the Debug Console input supports syntax coloring, indentation, auto closing of quotes, and other language features.

Debug Console

Annotation: You must be in a running debug session to utilise the Debug Panel REPL.

Redirect input/output to/from the debug target

Redirecting input/output is debugger/runtime specific, so VS Code does non take a built-in solution that works for all debuggers.

Here are two approaches yous might want to consider:

  1. Launch the program to debug ("debug target") manually in a terminal or command prompt and redirect input/output every bit needed. Make sure to pass the appropriate command line options to the debug target so that a debugger can attach to it. Create and run an "adhere" debug configuration that attaches to the debug target.

  2. If the debugger extension you are using tin can run the debug target in VS Code's Integrated Concluding (or an external terminal), y'all can attempt to pass the shell redirect syntax (for example, "<" or ">") every bit arguments.

Here'due south an case launch.json configuration:

                      {                                    "proper name"            :                        "launch program that reads a file from stdin"            ,                                    "type"            :                        "node"            ,                                    "asking"            :                        "launch"            ,                                    "programme"            :                        "programme.js"            ,                                    "console"            :                        "integratedTerminal"            ,                                    "args"            : [            "<"            ,                        "in.txt"            ]            }                  

This arroyo requires that the "<" syntax is passed through the debugger extension and ends up unmodified in the Integrated Final.

Multi-target debugging

For complex scenarios involving more than one procedure (for example, a client and a server), VS Code supports multi-target debugging.

Using multi-target debugging is simple: after yous've started a outset debug session, you can just launch another session. As presently equally a second session is up and running, the VS Code UI switches to multi-target mode:

Chemical compound launch configurations

An alternative way to start multiple debug sessions is past using a compound launch configuration. A compound launch configuration lists the names of two or more launch configurations that should exist launched in parallel. Optionally a preLaunchTask tin be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating 1 session will stop all of the compound sessions.

                      {                                    "version"            :                        "0.2.0"            ,                                    "configurations"            : [                          {                                    "blazon"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "proper name"            :                        "Server"            ,                                    "program"            :                        "${workspaceFolder}/server.js"                          },                          {                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "name"            :                        "Client"            ,                                    "program"            :                        "${workspaceFolder}/customer.js"                          }                          ],                                    "compounds"            : [                          {                                    "name"            :                        "Server/Customer"            ,                                    "configurations"            : [            "Server"            ,                        "Client"            ],                                    "preLaunchTask"            :                        "${defaultBuildTask}"            ,                                    "stopAll"            :                        truthful                          }                          ]            }                  

Compound launch configurations are displayed in the launch configuration dropdown carte.

Remote debugging

VS Code does non itself support remote debugging: this is a feature of the debug extension you are using, and you lot should consult the extension'southward folio in the Market for support and details.

There is, however, ane exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to larn how to configure this.

Automatically open a URI when debugging a server plan

Developing a spider web program typically requires opening a specific URL in a web browser in order to hit the server code in the debugger. VS Code has a built-in characteristic "serverReadyAction" to automate this task.

Here is an case of a unproblematic Node.js Express application:

                      var                                    express                          =                        require            (            'express'            );            var                                    app                          =                        express            ();            app            .            go            (            '/'            ,                        function            (            req            ,                        res            ) {                                    res            .            send            (            'Hello World!'            );            });            app            .            listen            (            3000            ,                        function            () {                                    panel            .            log            (            'Example app listening on port 3000!'            );            });                  

This awarding first installs a "How-do-you-do World" handler for the "/" URL and so starts to listen for HTTP connections on port 3000. The port is appear in the Debug Console, and typically, the programmer would now type http://localhost:3000 into their browser awarding.

The serverReadyAction feature makes information technology possible to add a structured property serverReadyAction to whatever launch config and select an "action" to exist performed:

                      {                                    "type"            :                        "node"            ,                                    "request"            :                        "launch"            ,                                    "name"            :                        "Launch Program"            ,                                    "program"            :                        "${workspaceFolder}/app.js"            ,                                    "serverReadyAction"            : {                                    "design"            :                        "listening on port ([0-ix]+)"            ,                                    "uriFormat"            :                        "http://localhost:%south"            ,                                    "action"            :                        "openExternally"                          }            }                  

Hither the pattern belongings describes the regular expression for matching the program's output string that announces the port. The pattern for the port number is put into parenthesis so that it is available every bit a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to excerpt a full URI.

The uriFormat property describes how the port number is turned into a URI. The first %s is substituted past the first capture group of the matching blueprint.

The resulting URI is and so opened exterior of VS Code ("externally") with the standard awarding configured for the URI's scheme.

Trigger Debugging via Edge or Chrome

Alternatively, the action can exist set to debugWithEdge or debugWithChrome. In this mode, a webRoot belongings can be added that is passed to the Chrome or Edge debug session.

To simplify things a fleck, most properties are optional and we use the following fallback values:

  • blueprint: "listening on.* (https?://\\S+|[0-9]+)" which matches the commonly used messages "listening on port 3000" or "Now listening on: https://localhost:5001".
  • uriFormat: "http://localhost:%southward"
  • webRoot: "${workspaceFolder}"

Triggering an Arbitrary Launch Config

In some cases, y'all may need to configure additional options for the browser debug session--or utilise a dissimilar debugger entirely. Yous tin can do this by setting activity to startDebugging with a name belongings ready to the proper name of the launch configuration to start when the design is matched.

The named launch configuration must be in the aforementioned file or binder every bit the one with the serverReadyAction.

Here the serverReadyAction feature in action:

Server ready feature in action

Next steps

To larn about VS Code'southward Node.js debugging support, take a look at:

  • Node.js - Describes the Node.js debugger, which is included in VS Code.
  • TypeScript - The Node.js debugger as well supports TypeScript debugging.

To encounter tutorials on the basics of Node.js debugging, cheque out these videos:

  • Intro Video - Debugging - Showcases the basics of debugging.
  • Getting started with Node.js debugging - Shows how to attach a debugger to a running Node.js process.

To acquire well-nigh debugging support for other programming languages via VS Code extensions:

  • C++
  • Python
  • Java

To learn about VS Code's job running support, go to:

  • Tasks - Describes how to run tasks with Gulp, Grunt, and Jake and how to bear witness errors and warnings.

To write your ain debugger extension, visit:

  • Debugger Extension - Uses a mock sample to illustrate the steps required to create a VS Code debug extension.

Mutual questions

What are the supported debugging scenarios?

Debugging of Node.js-based applications is supported on Linux, macOS, and Windows out of the box with VS Code. Many other scenarios are supported past VS Code extensions available in the Marketplace.

I do not see any launch configurations in the Run and Debug view dropdown. What is wrong?

The most common problem is that you did not set upwards launch.json or in that location is a syntax error in that file. Alternatively, you might need to open up a folder, since no-binder debugging does not back up launch configurations.

How To Add A Breakpoint In Visual Studio,

Source: https://code.visualstudio.com/docs/editor/debugging

Posted by: thomasmirs1957.blogspot.com

0 Response to "How To Add A Breakpoint In Visual Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel