Launch json vs code
Launch json vs code
Browser debugging in VS Code
Visual Studio Code includes a built-in debugger for Edge and Chrome. There are a couple ways to get started with it.
We also have more detailed walkthroughs to get started with React, Angular, Vue, and Ember, as well as other debugging recipes.
Open Link command
The simplest way to debug a webpage is through the Debug: Open Link command found in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). When you run this command, you’ll be prompted for a URL to open, and the debugger will be attached.
If your default browser is Edge, VS Code will use it to open the page. Otherwise, it will try to find an installation of Chrome on your system instead.
Launch configuration
Launch configs are the traditional way to set up debugging in VS Code, and provide you the most flexibility for running complex applications.
In this section, we’ll go into more detail about configurations and features for more advanced debugging scenarios. Instructions for Node.js debugging with source maps and stepping over external code also apply to browser-based debugging.
Note: If you are just getting started with VS Code, you can learn about general debugging features and creating launch.json configuration files in the Debugging topic.
Launching browsers
You can also debug a single file without running a server, for example:
Attaching to browsers
To attach to a running browser, it needs to be launched in a special debug mode. You can do this using the following command, replacing edge.exe with the path to your Edge or Chrome binary:
Next, add a new section to the vscode/launch.json file as below:
Now, you can press F5 or the Start button in the Run and Debug view to attach to the running browser. You can even add a host property to debug a browser running on a different machine.
Launch configuration attributes
Below is a reference of common launch.json attributes specific to browser debugging. You can view the complete set of options in the vscode-js-debug options documentation.
These attributes are only available for launch configurations of request type launch :
These attributes are only available for launch configurations of request type attach :
Configure C/C++ debugging
A launch.json file is used to configure the debugger in Visual Studio Code.
The generated file contains two sections, one that configures debugging for launch and a second that configures debugging for attach.
Configure VS Code’s debugging behavior
Set or change the following options to control VS Code’s behavior during debugging:
program (required)
Specifies the full path to the executable the debugger will launch or attach to. The debugger requires this location in order to load debug symbols.
symbolSearchPath
requireExactSource
An optional flag that tells the Visual Studio Windows Debugger to require current source code to match the pdb.
additionalSOLibSearchPath
externalConsole
avoidWindowsConsoleRedirection
In order to support VS Code’s Integrated Terminal with gdb on Windows, the extension adds console redirection commands to the debuggee’s arguments to have console input and output show up in the integrated terminal. Setting this option to true will disable it.
logging
Optional flags to determine what types of messages should be logged to the Debug Console.
visualizerFile
.natvis file to be used when debugging. See Create custom views of native objects for information on how to create Natvis files.
showDisplayString
When a visualizerFile is specified, showDisplayString will enable the display string. Turning on this option can cause slower performance during debugging.
Example:
Configure the target application
The following options enable you to modify the state of the target application when it is launched:
Sets the working directory of the application launched by the debugger.
environment
Example:
Customizing GDB or LLDB
You can change the behavior of GDB or LLDB by setting the following options:
MIMode
miDebuggerPath
The path to the debugger (such as gdb). When only the executable is specified, it will search the operating system’s PATH variable for a debugger (GDB on Linux and Windows, LLDB on OS X).
miDebuggerArgs
Additional arguments to pass to the debugger (such as gdb).
stopAtEntry
stopAtConnect
setupCommands
customLaunchSetupCommands
launchCompleteCommand
The command to execute after the debugger is fully set up in order to cause the target process to run. Allowed values are «exec-run», «exec-continue», «None». The default value is «exec-run».
Example:
symbolLoadInfo
Debugging dump files
The C/C++ extension enables debugging dump files on Windows and core dump files Linux and OS X.
dumpPath
If you want to debug a Windows dump file, set this to the path to the dump file to start debugging in the launch configuration.
coreDumpPath
Full path to a core dump file to debug for the specified program. Set this to the path to the core dump file to start debugging in the launch configuration. Note: core dump debugging is not supported with MinGw.
Remote debugging or debugging with a local debugger server
miDebuggerServerAddress
Network address of the debugger server (for example, gdbserver) to connect to for remote debugging (example: localhost:1234 ).
debugServerPath
Full path to debug server to launch.
debugServerArgs
Arguments for the debugger server.
serverStarted
Server-started pattern to look for in the debug server output. Regular expressions are supported.
filterStdout
filterStderr
serverLaunchTimeout
Time in milliseconds, for the debugger to wait for the debugServer to start up. Default is 10000.
pipeTransport
For information about attaching to a remote process, such as debugging a process in a Docker container, see the Pipe transport settings article.
hardwareBreakpoints
Additional properties
processId
request
Indicates whether the configuration section is intended to launch the program or attach to an already running instance.
targetArchitecture
Deprecated This option is no longer needed as the target architecture is automatically detected.
Indicates the underlying debugger being used. Must be cppvsdbg when using the Visual Studio Windows debugger, and cppdbg when using GDB or LLDB. This is automatically set to the correct value when the launch.json file is created.
sourceFileMap
Environment variable definitions file
The cppvsdbg debugger configuration also contains an envFile property that allows you to easily set variables for debugging purposes.
project.env file:
Symbol Options
The symbolOptions element allows customization of how the debugger searches for symbols. Example:
Properties
cachePath«: Directory where symbols downloaded from symbol servers should be cached. If unspecified, the debugger will default to %TEMP%\SymbolCache..
Launch json vs code
Configure C/C++ debugging
A launch.json file is used to configure the debugger in Visual Studio Code.
The generated file contains two sections, one that configures debugging for launch and a second that configures debugging for attach.
Configure VS Code’s debugging behavior
Set or change the following options to control VS Code’s behavior during debugging:
Specifies the full path to the executable the debugger will launch or attach to. The debugger requires this location in order to load debug symbols.
An optional flag that tells the Visual Studio Windows Debugger to require current source code to match the pdb.
In order to support VS Code’s Integrated Terminal with gdb on Windows, the extension adds console redirection commands to the debuggee’s arguments to have console input and output show up in the integrated terminal. Setting this option to true will disable it.
Optional flags to determine what types of messages should be logged to the Debug Console.
.natvis file to be used when debugging. See Create custom views of native objects for information on how to create Natvis files.
When a visualizerFile is specified, showDisplayString will enable the display string. Turning on this option can cause slower performance during debugging.
Example:
Configure the target application
The following options enable you to modify the state of the target application when it is launched:
Sets the working directory of the application launched by the debugger.
Example:
Customizing GDB or LLDB
You can change the behavior of GDB or LLDB by setting the following options:
The path to the debugger (such as gdb). When only the executable is specified, it will search the operating system’s PATH variable for a debugger (GDB on Linux and Windows, LLDB on OS X).
Additional arguments to pass to the debugger (such as gdb).
The command to execute after the debugger is fully set up in order to cause the target process to run. Allowed values are «exec-run», «exec-continue», «None». The default value is «exec-run».
Example:
Debugging dump files
The C/C++ extension enables debugging dump files on Windows and core dump files Linux and OS X.
If you want to debug a Windows dump file, set this to the path to the dump file to start debugging in the launch configuration.
Full path to a core dump file to debug for the specified program. Set this to the path to the core dump file to start debugging in the launch configuration. Note: core dump debugging is not supported with MinGw.
Remote debugging or debugging with a local debugger server
Network address of the debugger server (for example, gdbserver) to connect to for remote debugging (example: localhost:1234 ).
Full path to debug server to launch.
Arguments for the debugger server.
Server-started pattern to look for in the debug server output. Regular expressions are supported.
Time in milliseconds, for the debugger to wait for the debugServer to start up. Default is 10000.
For information about attaching to a remote process, such as debugging a process in a Docker container, see the Pipe transport settings article.
Indicates whether the configuration section is intended to launch the program or attach to an already running instance.
Deprecated This option is no longer needed as the target architecture is automatically detected.
Indicates the underlying debugger being used. Must be cppvsdbg when using the Visual Studio Windows debugger, and cppdbg when using GDB or LLDB. This is automatically set to the correct value when the launch.json file is created.
Environment variable definitions file
The cppvsdbg debugger configuration also contains an envFile property that allows you to easily set variables for debugging purposes.
project.env file:
The symbolOptions element allows customization of how the debugger searches for symbols. Example:
cachePath«: Directory where symbols downloaded from symbol servers should be cached. If unspecified, the debugger will default to %TEMP%\SymbolCache..
Properties for «loadAllButExcluded» mode
moduleFilter.excludedModules: Array of modules that the debugger should NOT load symbols for. Wildcards (example: MyCompany.*.dll) are supported.
Properties for «loadOnlyIncluded» mode
Debugging
One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.
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, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace 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 best for you.
Start debugging
The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.
It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.
Run and Debug view
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.
Run menu
The top-level Run menu has the most common run and debug commands:
Launch configurations
To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.
To create a launch.json file, click the create a launch.json file link in the Run start view.
VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:
Here is the launch configuration generated for Node.js debugging:
Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.
Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.
Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.
Review all automatically generated values and make sure that they make sense for your project and debugging environment.
Launch versus attach configurations
In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.
If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’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 mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.
VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.
Add a new configuration
VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.
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 want to debug.
As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):
In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.
Debug actions
Once a debug session starts, the Debug toolbar will appear on the top of the editor.
Run mode
In addition to debugging a program, 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’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.
Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.
Breakpoints
Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.
If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.
The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.
Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :
Logpoints
A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.
A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.
Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.
Data inspection
Variables can be 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 CALL STACK section.
Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.
Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.
Variable names and values can be filtered by typing while the focus is on the VARIABLES section.
Launch.json attributes
There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.
The following attributes are mandatory for every launch configuration:
Here are some optional attributes available to all launch configurations:
Many debuggers support some of the following attributes:
Variable substitution
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:
Valid operating properties are «windows» for Windows, «linux» for Linux, and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.
Please note that the type property cannot be 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 program always stops on entry except on macOS:
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:
Advanced breakpoint topics
Conditional breakpoints
A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.
You can add a condition and/or hit 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:
Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.
An example of condition editing in the BREAKPOINTS view:
If a debugger does not 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 column 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 can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.
Function breakpoints
Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function 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 get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.
Debug Console REPL
Note: You must be in a running debug session to use the Debug Console REPL.
Redirect input/output to/from the debug target
Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.
Here are two approaches you might want to consider:
Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as 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 «attach» debug configuration that attaches to the debug target.
If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, » «) as arguments.
Here’s an example launch.json configuration:
This approach requires that the » preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.
Compound launch configurations are displayed in the launch configuration dropdown menu.
Remote debugging
VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.
There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.
Automatically open a URI when debugging a server program
Developing a 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 feature «serverReadyAction» to automate this task.
Here is an example of a simple Node.js Express application:
This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.
The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:
Here the pattern property 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 as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.
The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.
The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.
Trigger Debugging via Edge or Chrome
To simplify things a bit, most properties are optional and we use the following fallback values:
Triggering an Arbitrary Launch Config
In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.
Here the serverReadyAction feature in action:
Next steps
To learn about VS Code’s Node.js debugging support, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about debugging support for other programming languages via VS Code extensions:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
Node.js debugging in VS Code
The Visual Studio Code editor has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, and many other languages that are transpiled into JavaScript. Setting up a project for Node.js debugging is straightforward with VS Code providing appropriate launch configuration defaults and snippets.
There are a few ways you can debug your Node.js programs in VS Code:
Auto Attach
If the Auto Attach feature is enabled, the Node debugger automatically attaches to certain Node.js processes that have been launched from VS Code’s Integrated Terminal. To enable the feature, either use the Toggle Auto Attach command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) or, if it’s already activated, use the Auto Attach Status bar item.
There are three modes for auto attach, which you can select in the resulting Quick Pick and via the debug.javascript.autoAttachFilter setting:
After enabling Auto Attach, you’ll need to restart your terminal. This can be done by clicking the ⚠ icon in the top right of the terminal, or just creating a new one. Then, the debugger should attach to your program within a second:
When auto attach is on, the Auto Attach item will appear in the status bar across the bottom of the VS Code window. Clicking it allows you to change the auto attach mode, or temporarily turn it off. Temporarily turning off auto attach is useful if you’re running some one-off programs where you don’t need debugging, but you don’t want to disable the feature entirely.
Additional Configuration
Other Launch Configuration Properties
You can apply other properties normally found in launch.json to auto attach in the debug.javascript.terminalOptions setting. For example, to add node internals to your skipFiles, you could add the following to your user or workspace settings:
Auto Attach Smart Patterns
In smart Auto Attach mode, VS Code will try to attach to your code, and not attach to build tools you aren’t interested in debugging. It does this by matching the main script against a list of glob patterns. The glob patterns are configurable in the debug.javascript.autoAttachSmartPattern setting, which defaults to:
JavaScript Debug Terminal
In a similar way to auto attach, the JavaScript Debug Terminal will automatically debug any Node.js process you run in it. You can create a Debug Terminal by running the Debug: Create JavaScript Debug Terminal command from the Command Palette ( kbs(workbench.action.showCommands) ), or by selecting the Create JavaScript Debug Terminal from the terminal switcher dropdown.
Additional Configuration
Other Launch Configuration Properties
You can apply other properties normally found in launch.json to the debug terminal in the debug.javascript.terminalOptions setting. For example, to add node internals to your skipFiles, you could add the following to your user or workspace settings:
Launch Configuration
Launch configs are the traditional way to set up debugging in VS Code, and provide you the most configuration options for running complex applications.
In this section we’ll go into more detail about configurations and features for more advanced debugging scenarios. You’ll find instruction for debugging with source maps, stepping over external code, doing remote debugging, and much more.
If you’d like to watch an introductory video, see Getting started with Node.js debugging.
Note: If you are just getting started with VS Code, you can learn about general debugging features and creating launch.json configuration files in the Debugging topic.
Launch configuration attributes
Below is a reference of common launch.json attributes specific to the Node.js debugger. You can view the complete set of options in the vscode-js-debug options documentation.
The following attributes are supported in launch configurations of type launch and attach :
These attributes are only available for launch configurations of request type launch :
This attribute is only available for launch configurations of request type attach :
Launch configurations for common scenarios
You can trigger IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) in your launch.json file to see launch configuration snippets for commonly used Node.js debugging scenarios.
You can also bring up the snippets with the Add Configuration. button in the lower right of the launch.json editor window.
These are the available snippets:
Node console
Launch configuration support for ‘npm’ and other tools
Instead of launching the Node.js program directly with node, you can use ‘npm’ scripts or other task runner tools directly from a launch configuration:
Let’s look at an ‘npm’ example. If your package.json has a ‘debug’ script, for example:
the corresponding launch configuration would look like this:
Multi version support
If you are using ‘nvm’ (or ‘nvm-windows’) to manage your Node.js versions, it is possible to specify a runtimeVersion attribute in a launch configuration for selecting a specific version of Node.js:
If you are using ‘nvs’ to manage your Node.js versions, it is possible to use runtimeVersion attribute to select a specific version, architecture, and flavor Node.js, for example:
Make sure to have those Node.js versions installed that you want to use with the runtimeVersion attribute, as the feature will not download and install the version automatically. For example, you’ll have to run something like nvm install 7.10.1 or nvs add 7.10.1 from the integrated terminal if you plan to add «runtimeVersion»: «7.10.1» to your launch configuration.
Load environment variables from external file
The VS Code Node debugger supports loading environment variables from a file and passing them to the Node.js runtime. To use this feature, add an attribute envFile to your launch configuration and specify the absolute path to the file containing the environment variables:
Any environment variable specified in the env dictionary will override variables loaded from the file.
Attaching to Node.js
If you want to attach the VS Code debugger to an external Node.js program, launch Node.js as follows:
or if the program shouldn’t start running, but must wait for the debugger to attach:
Now you have a couple options for attaching the debugger to your program:
Let’s go through these options in detail:
Attach to Node Process action
The Attach to Node Process command from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) opens a Quick Pick menu that lists all potential processes that are available to the Node.js debugger:
The individual processes listed in the picker show the debug port and process ID. Once you select your Node.js process in that list, the Node.js debugger will try to attach to it.
Setting up an «Attach» configuration
This option requires more work but in contrast to the previous two options it allows you to configure various debug configuration options explicitly.
The simplest «attach» configuration looks like this:
If you want to attach to a Node.js process that hasn’t been started in debug mode, you can do this by specifying the process ID of the Node.js process as a string:
Since it is a bit laborious to repeatedly find the process ID and enter it in the launch configuration, Node debug supports a command variable PickProcess that will open the process picker (from above).
Using the PickProcess variable the launch configuration looks like this:
Stop debugging
Using the Debug: Stop action (available in the Debug toolbar or via the Command Palette) stops the debug session.
If the debug session was started in «attach» mode (and the red terminate button in the Debug toolbar shows a superimposed «plug»), pressing Stop disconnects the Node.js debugger from the debuggee that then continues execution.
If the debug session is in «launch» mode, pressing Stop does the following:
When pressing Stop for the first time, the debuggee is requested to shut down gracefully by sending a SIGINT signal. The debuggee is free to intercept this signal and clean up anything as necessary and then shut down. If there are no breakpoints (or problems) in that shutdown code, the debuggee and the debug session will terminate.
However if the debugger hits a breakpoint in the shutdown code or if the debuggee does not terminate properly by itself, then the debug session will not end. In this case, pressing Stop again will force terminate the debuggee and its child processes ( SIGKILL ).
So if you see that a debug session doesn’t end when you press the red Stop button, then press the button again to force a shutdown of the debuggee.
Note that on the Windows operating system, pressing Stop always forcibly kills the debuggee and its child processes.
Source maps
The JavaScript debugger of VS Code supports source maps that help debugging of transpiled languages, for example, TypeScript or minified/uglified JavaScript. With source maps, it’s possible to single step through or set breakpoints in the original source. If no source map exists for the original source, or if the source map is broken and cannot successfully map between the source and the generated JavaScript, then breakpoints show up as unverified (gray hollow circles).
Tool Configuration
Since source maps are not always automatically created, you should make sure to configure your transpiler to create them. For example:
TypeScript
Babel
Webpack
Webpack has numerous source map options. We recommend setting the property devtool: «source-map» in your webpack.config.js for the best fidelity of results, although you can experiment with other settings causes slowdowns in your build.
Also, if you have additional compilation steps in webpack, such as using a TypeScript loader, you’ll also want to make sure that those steps are set up to generate sourcemaps. Otherwise, the sourcemaps that webpack generates will map back to the compiled code from the loader, instead of the real sources.
Source Map Discovery
Source Map Resolution
Smart stepping
With the smartStep attribute set to true in a launch configuration, VS Code will automatically skip ‘uninteresting code’ when stepping through code in the debugger. ‘Uninteresting code’ is code that is generated by a transpiling process but is not covered by a source map so it does not map back to the original source. This code gets in your way when stepping through source code in the debugger because it makes the debugger switch between the original source code and generated code that you are not interested in. smartStep will automatically step through code not covered by a source map until it reaches a location that is covered by a source map again.
Smart stepping is especially useful for cases like async/await downcompilation in TypeScript, where the compiler injects helper code that is not covered by a source map.
The smartStep feature only applies to JavaScript code that was generated from source and therefore has a source map. For JavaScript without sources, the smart stepping option has no effect.
JavaScript source map tips
Here are some things to try when your breakpoints turn gray:
Remote debugging
Note: VS Code now has universal remote development capabilities. Using the Remote Development extensions, Node.js development in remote scenarios and containers is no different than Node.js development in a local setup. This is the recommended way to remote debug Node.js programs. Check out the Getting started section and Remote tutorials to learn more.
If you are unable to use any of the Remote Development extensions to debug your Node.js program, below is a guide on how to debug a remote Node.js program from your local instance of VS Code.
The Node.js debugger supports remote debugging where you attach to a process running on a different machine, or in a container. Specify a remote host via the address attribute. For example:
Access Loaded Scripts
If you need to set a breakpoint in a script that is not part of your workspace and therefore cannot be easily located and opened through normal VS Code file browsing, you can access the loaded scripts via the LOADED SCRIPTS view in the Run and Debug view:
The LOADED SCRIPTS view lets you quickly select the script by typing its name or filter the list when Enable Filter on Type is on.
Scripts are loaded into a read-only editor where you can set breakpoints. These breakpoints are remembered across debug sessions but you only have access to the script content while a debug session is running.
Restarting debug sessions automatically when source is edited
The restart attribute of a launch configuration controls whether the Node.js debugger automatically restarts after the debug session has ended. This feature is useful if you use nodemon to restart Node.js on file changes. Setting the launch configuration attribute restart to true makes the node debugger automatically try to reattach to Node.js after Node.js has terminated.
If you have started your program server.js via nodemon on the command line like this:
you can attach the VS Code debugger to it with the following launch configuration:
Alternatively you can start your program server.js via nodemon directly with a launch config and attach the VS Code debugger:
Tip: Pressing the Stop button stops the debug session and disconnects from Node.js, but nodemon (and Node.js) will continue to run. To stop nodemon, you will have to kill it from the command line (which is easily possible if you use the integratedTerminal as shown above).
Tip: In case of syntax errors, nodemon will not be able to start Node.js successfully until the error has been fixed. In this case, VS Code will continue trying to attach to Node.js but eventually give up (after 10 seconds). To avoid this, you can increase the timeout by adding a timeout attribute with a larger value (in milliseconds).
Restart frame
The Node debugger supports restarting execution at a stack frame. This can be useful in situations where you have found a problem in your source code and you want to rerun a small portion of the code with modified input values. Stopping and then restarting the full debug session can be time-consuming. The Restart Frame action allows you to reenter the current function after you have changed variables with the Set Value action:
Restart Frame won’t roll back mutation to state outside of the function, so it may not always work as expected.
Breakpoints
Conditional Breakpoints
Conditional breakpoints are breakpoints that only pause when an expression returns a truthy value. You can create one by right-clicking in the gutter beside a line number and selecting «Conditional Breakpoint»:
Logpoints
Sometimes you want to just log a message or value when code hits a certain location, rather than pausing. You can do this with logpoints. Logpoints don’t pause, but rather log a message to the Debug Console when hit. In the JavaScript debugger, you can use curly braces to interpolate expressions into the message, like current value is:
You can create one by right-clicking in the gutter beside a line number and selecting «Logpoint». For example, this might log something like location is /usr/local :
Hit count breakpoints
The ‘hit count condition’ controls how many times a breakpoint needs to be hit before it will ‘break’ execution. You can place a hit count breakpoint by right-clicking in the gutter beside a line number, selecting «Conditional Breakpoint», and then switching to «Hit Count».
Breakpoint validation
For performance reasons, Node.js parses the functions inside JavaScript files lazily on first access. As a consequence, breakpoints don’t work in source code areas that haven’t been seen (parsed) by Node.js.
When doing so, you will find that some of your breakpoints don’t «stick» to the line requested but instead «jump» for the next possible line in already-parsed code. To avoid confusion, VS Code always shows breakpoints at the location where Node.js thinks the breakpoint is. In the BREAKPOINTS section, these breakpoints are shown with an arrow between requested and actual line number:
This breakpoint validation occurs when a session starts and the breakpoints are registered with Node.js, or when a session is already running and a new breakpoint is set. In this case, the breakpoint may «jump» to a different location. After Node.js has parsed all the code (for example, by running through it), breakpoints can be easily reapplied to the requested locations with the Reapply button in the BREAKPOINTS section header. This should make the breakpoints «jump back» to the requested location.
Skipping uninteresting code
VS Code Node.js debugging has a feature to avoid source code that you don’t want to step through (also known as ‘Just My Code’). This feature can be enabled with the skipFiles attribute in your launch configuration. skipFiles is an array of glob patterns for script paths to skip.
all code in the node_modules and lib folders in your project will be skipped. The skipFiles also apply to the location shown when calling console.log and similar methods: the first non-skipped location in the stack will be shown beside the output in the Debug Console.
Built-in core modules of Node.js can be referred to by the ‘magic name’ in a glob pattern. The following example skips all internal modules:
The exact ‘skipping’ rules are as follows:
Skipped source is shown in a ‘dimmed’ style in the CALL STACK view:
Hovering over the dimmed entries explains why the stack frame is dimmed.
A context menu item on the call stack, Toggle skipping this file enables you to easily skip a file at runtime without adding it to your launch config. This option only persists for the current debugging session. You can also use it to stop skipping a file that is skipped by the skipFiles option in your launch config.
Note: The legacy protocol debugger supports negative glob patterns, but they must follow a positive pattern: positive patterns add to the set of skipped files, while negative patterns subtract from that set.
In the following ( legacy protocol-only) example all but a ‘math’ module is skipped:
Note: The legacy protocol debugger has to emulate the skipFiles feature because the V8 Debugger Protocol does not support it natively. This might result in slow stepping performance.
Supported Node-like runtimes
The current VS Code JavaScript debugger supports Node version at or above 8.x, recent Chrome versions, and recent Edge versions (via the msedge launch type).
Next steps
In case you didn’t already read the Node.js section, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
Common questions
Can I debug if I’m using symlinks?
If your main script is inside a symlinked path, then you will also need to add the «—preserve-symlinks-main» option. This option is only available in Node 10+.
How do I debug ECMAScript modules?
Customize build and debug tasks for «Open Folder» development
Visual Studio knows how to run many different languages and codebases, but it doesn’t know how to run everything. If you opened a code folder in Visual Studio, and Visual Studio knows how to run your code, you can run it right away without any additional configuration.
If the codebase uses custom build tools that Visual Studio doesn’t recognize, you need to provide some configuration details to run and debug the code in Visual Studio. You instruct Visual Studio how to build your code by defining build tasks. You can create one or more build tasks to specify all the items a language needs to build and run its code. You can also create arbitrary tasks that can do nearly anything you want. For example, you can create a task to list the contents of a folder or to rename a file.
Customize your project-less codebase by using the following .json files:
File name | Purpose |
---|---|
tasks.vs.json | Specify custom build commands and compiler switches, and arbitrary (non-build related) tasks. Accessed via the Solution Explorer right-click menu item Configure Tasks. |
launch.vs.json | Specify command-line arguments for debugging. Accessed via the Solution Explorer right-click menu item Debug and Launch Settings. |
These .json files are located in a hidden folder called .vs in the root folder of your codebase. The tasks.vs.json and launch.vs.json files are created by Visual Studio on an as-needed basis when you choose either Configure Tasks or Debug and Launch Settings on a file or folder in Solution Explorer. These .json files are hidden because users generally don’t want to check them into source control. However, if you want to be able to check them into source control, drag the files into the root of your codebase by using your file system, where they then are visible in Solution Explorer and to source control.
To view hidden files in Visual Studio, choose the Show All Files button on the Solution Explorer toolbar.
Define tasks with tasks.vs.json
You can automate build scripts or any other external operations on the files you have in your current workspace by running them as tasks directly in the IDE. You can configure a new task by right-clicking on a file or folder and selecting Configure Tasks.
This creates (or opens) the tasks.vs.json file in the .vs folder. You can define a build task or arbitrary task in this file, and then invoke it using the name you gave it from the Solution Explorer right-click menu.
Custom tasks can be added to individual files, or to all files of a specific type. For instance, NuGet package files can be configured to have a «Restore Packages» task, or all source files can be configured to have a static analysis task, such as a linter for all .js files.
Define custom build tasks
If your codebase uses custom build tools that Visual Studio doesn’t recognize, then you cannot run and debug the code in Visual Studio until you complete some configuration steps. Visual Studio provides build tasks where you can tell Visual Studio how to build, rebuild, and clean your code. The tasks.vs.json build task file couples the Visual Studio inner development loop to the custom build tools used by your codebase.
Consider a codebase that consists of a single C# file called hello.cs. The makefile for such a codebase might look like this:
For such a makefile that contains build, clean, and rebuild targets, you can define the following tasks.vs.json file. It contains three build tasks for building, rebuilding, and cleaning the codebase, using NMAKE as the build tool.
After you define build tasks in tasks.vs.json, additional right-click menu (context menu) items are added to the corresponding files in Solution Explorer. For this example, «build», «rebuild», and «clean» options are added to the context menu of any makefile files.
The commands appear in the context menu under the Configure Tasks command due to their contextType settings. «build», «rebuild», and «clean» are build commands, so they appear in the build section in the middle of the context menu.
When you select one of these options, the task executes. Output appears in the Output window, and build errors appear in the Error List.
Define arbitrary tasks
You can define arbitrary tasks in the tasks.vs.json file, to do just about anything you want. For example, you can define a task to display the name of the currently selected file in the Output window, or to list the files in a specified directory.
The following example shows a tasks.vs.json file that defines a single task. When invoked, the task displays the filename of the currently selected .js file.
After saving tasks.vs.json, you can right-click on any .js file in the folder and choose Echo filename. The file name is displayed in the Output window.
If your codebase doesn’t contain a tasks.vs.json file, you can create one by choosing Configure Tasks from the right-click or context menu of a file in Solution Explorer.
The next example defines a task that lists the files and subfolders of the bin directory.
This task applies to all files. When you open the context menu on any file in Solution Explorer, the task’s name List Outputs appears at the bottom of the menu. When you choose List Outputs, the contents of the bin directory are listed in the Output window in Visual Studio.
Settings scope
Multiple tasks.vs.json files can exist at the root and subdirectories of a codebase. This design enables the flexibility to have different behavior in different subdirectories of the codebase. Visual Studio aggregates or overrides settings throughout the codebase, prioritizing files in the following order:
These aggregation rules apply to tasks.vs.json. For information on how settings in other file are aggregated, see the corresponding section for that file in this article.
Properties for tasks.vs.json
This section describes some of the properties you can specify in tasks.vs.json.
appliesTo
File mask | Description |
---|---|
«*» | task is available to all files and folders in the workspace |
«*/» | task is available to all folders in the workspace |
«*.js» | task is available to all files with the extension .js in the workspace |
«/*.js» | task is available to all files with the extension .js in the root of the workspace |
«src/*/» | task is available to all subfolders of the src folder |
«makefile» | task is available to all makefile files in the workspace |
«/makefile» | task is available only to the makefile in the root of the workspace |
Macros for tasks.vs.json
Configure debugging with launch.vs.json
To configure CMake projects for debugging, see Configure CMake debugging sessions.
To configure your codebase for debugging, in Solution Explorer choose the Debug and Launch Settings menu item from the right-click or context menu of your executable file.
In the Select a Debugger dialog box, choose an option, and then choose the Select button.
If the launch.vs.json file doesn’t already exist, it is created.
Next, right-click on the executable file in Solution Explorer, and choose Set as Startup Item.
The executable is designated as the startup item for your codebase, and the debugging Start button’s title changes to reflect the name of your executable.
When you choose F5, the debugger launches and stops at any breakpoint you may have already set. All the familiar debugger windows are available and functional.
For additional details about custom build and debug tasks in C++ open folder projects, see Open Folder support for C++ build systems in Visual Studio.
Specify arguments for debugging
You can specify command-line arguments to pass in for debugging in the launch.vs.json file. Add the arguments in the args array, as shown in the following example:
When you save this file, the name of the new configuration appears in the debug target drop-down list, and you can select it to start the debugger. You can create as many debug configurations as you like.
The configurations array property in launch.vs.json is read from two file locations—the root directory for the codebase, and the .vs directory. If there is a conflict, priority is given to the value in .vs\launch.vs.json.
Additional settings files
In addition to the three .json files described in this topic, Visual Studio also reads settings from some additional files, if they exist in your codebase.
.vscode\settings.json
You can have any number of .vscode\settings.json files in your codebase. Settings read from this file are applied to the parent directory of .vscode and all of its subdirectories.
.gitignore
.gitignore files are used to tell Git which files to ignore; that is, which files and directories you don’t want to check in. .gitignore files are usually included as part of a codebase so that the settings can be shared with all developers of the codebase. Visual Studio reads patterns in .gitignore files to filter items visually and from some search tools.
Settings read from the .gitignore file are applied to its parent directory and all subdirectories.
Python debugging in VS Code
For general debugging features such as inspecting variables, setting breakpoints, and other activities that aren’t language-dependent, review VS Code debugging.
This article mainly addresses Python-specific debugging configurations, including the necessary steps for specific app types and remote debugging.
Initialize configurations
Note: To change debugging configuration, your code must be stored in a folder.
To initialize debug configurations, first select the Run view in the sidebar:
If you don’t yet have any configurations defined, you’ll see a button to Run and Debug and a link to create a configuration (launch.json) file:
To generate a launch.json file with Python configurations, do the following steps:
Select the create a launch.json file link (outlined in the image above) or use the Run > Open configurations menu command.
A configuration menu will open from the Command Palette allowing you to choose the type of debug configuration you want for the opened file. For now, in the Select a debug configuration menu that appears, select Python File.
Note: Starting a debugging session through the Debug Panel, F5 or Run > Start Debugging when no configuration exists will also bring up the debug configuration menu, but will not create a launch.json file.
The Python extension then creates and opens a launch.json file that contains a pre-defined configuration based on what you previously selected, in this case, Python File. You can modify configurations (to add arguments, for example), and also add custom configurations.
The details of configuration properties are covered later in this article under Standard configuration and options. Other configurations are also described in this article under Debugging specific app types.
Additional configurations
By default, VS Code shows only the most common configurations provided by the Python extension. You can select other configurations to include in launch.json by using the Add Configuration command shown in the list and the launch.json editor. When you use the command, VS Code prompts you with a list of all available configurations (be sure to select the Python option):
Selecting the Attach using Process ID one yields the following result:
See Debugging specific app types for details on all of these configurations.
During debugging, the Status Bar shows the current configuration and the current debugging interpreter. Selecting the configuration brings up a list from which you can choose a different configuration:
By default, the debugger uses the same interpreter selected for your workspace, just like other features of Python extension for VS Code. To use a different interpreter for debugging specifically, set the value for python in launch.json for the applicable debugger configuration. Alternately, select the named interpreter on the Status Bar to select a different one.
Basic debugging
If you’re only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.
If you’re looking to debug a web application using Flask, Django or FastAPI, the Python extension provides dynamically created debug configurations based on your project structure under the Show all automatic debug configurations option, through the Run and Debug view.
But if you’re looking to debug other kinds of applications, you can start the debugger through the Run view by clicking on the Run and Debug button.
When no configuration has been set, you’ll be given a list of debugging options. Here, you can select the appropriate option to quickly debug your code.
Two common options are to use the Python File configuration to run the currently open Python file or to use the Attach using Process ID configuration to attach the debugger to a process that is already running.
For information about creating and using debugging configurations, see the Initialize configurations and Additional configurations sections. Once a configuration is added, it can be selected from the dropdown list and started using the Start Debugging button.
Command line debugging
The debugger can also be run from the command line. The debugger command line syntax is as follows:
You would then use the following configuration to attach from the VS Code Python extension.
Note: Specifying host is optional for listen, by default 127.0.0.1 is used.
If you wanted to debug remote code or code running in a docker container, on the remote machine or container, you would need to modify the previous CLI command to specify a host.
The associated configuration file would then look as follows.
Note: Be aware that when you specify a host value other than 127.0.0.1 or localhost you are opening a port to allow access from any machine, which carries security risks. You should make sure that you’re taking appropriate security precautions, such as using SSH tunnels, when doing remote debugging.
Flag | Options | Description |
---|---|---|
—listen or —connect | [ :] |
Debugging by attaching over a network connection
Local script debugging
There may be instances where you need to debug a Python script that’s invoked locally by another process. For example, you may be debugging a web server that runs different Python scripts for specific processing jobs. In such cases, you need to attach the VS Code debugger to the script once it’s been launched:
Run VS Code, open the folder or workspace containing the script, and create a launch.json for that workspace if one doesn’t exist already.
In the script code, add the following and save the file:
Open a terminal using Terminal: Create New Terminal, which activates the script’s selected environment.
Switch to the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ), select the appropriate configuration from the debugger dropdown list, and start the debugger.
Remote script debugging with SSH
Remote debugging allows you to step through a program locally within VS Code while it runs on a remote computer. It is not necessary to install VS Code on the remote computer. For added security, you may want or need to use a secure connection, such as SSH, to the remote computer when debugging.
Note: On Windows computers, you may need to install Windows 10 OpenSSH to have the ssh command.
The following steps outline the general process to set up an SSH tunnel. An SSH tunnel allows you to work on your local machine as if you were working directly on the remote in a more secure manner than if a port was opened for public access.
On the remote computer:
Enable port forwarding by opening the sshd_config config file (found under /etc/ssh/ on Linux and under %programfiles(x86)%/openssh/etc on Windows) and adding or modifying the following setting:
Note: The default for AllowTcpForwarding is yes, so you might not need to make a change.
On the local computer:
Verify that you can see a prompt in the SSH session.
Starting debugging
Now that an SSH tunnel has been set up to the remote computer, you can begin your debugging.
Both computers: make sure that identical source code is available.
Remote computer: there are two ways to specify how to attach to the remote process.
In the source code, add the following lines, replacing address with the remote computer’s IP address and port number (IP address 1.2.3.4 is shown here for illustration only).
The IP address used in listen should be the remote computer’s private IP address. You can then launch the program normally, causing it to pause until the debugger attaches.
Launch the remote process through debugpy, for example:
Local computer: Only if you modified the source code on the remote computer as outlined above, then in the source code, add a commented-out copy of the same code added on the remote computer. Adding these lines makes sure that the source code on both computers matches line by line.
Local computer: switch to the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) in VS Code, select the Python: Attach configuration
Local computer: set a breakpoint in the code where you want to start debugging.
Local computer: start the VS Code debugger using the modified Python: Attach configuration and the Start Debugging button. VS Code should stop on your locally set breakpoints, allowing you to step through the code, examine variables, and perform all other debugging actions. Expressions that you enter in the Debug Console are run on the remote computer as well.
Text output to stdout, as from print statements, appears on both computers. Other outputs, such as graphical plots from a package like matplotlib, however, appear only on the remote computer.
During remote debugging, the debugging toolbar appears as below:
On this toolbar, the disconnect button ( ⇧F5 (Windows, Linux Shift+F5 ) ) stops the debugger and allows the remote program to run to completion. The restart button ( ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 ) ) restarts the debugger on the local computer but does not restart the remote program. Use the restart button only when you’ve already restarted the remote program and need to reattach the debugger.
Set configuration options
Provides the name for the debug configuration that appears in the VS Code dropdown list.
Identifies the type of debugger to use; leave this set to python for Python code.
request
Specifies the mode in which to start debugging:
program
You can also rely on a relative path from the workspace root. For example, if the root is /Users/Me/Projects/PokemonGo-Bot then you can use the following example:
module
python
The full path that points to the Python interpreter to be used for debugging.
Alternately, you can use a custom environment variable that’s defined on each platform to contain the full path to the Python interpreter to use, so that no other folder paths are needed.
If you need to pass arguments to the Python interpreter, you can use the pythonArgs property.
pythonArgs
Specifies arguments to pass to the Python program. Each element of the argument string that’s separated by a space should be contained within quotes, for example:
stopOnEntry
console
Specifies how program output is displayed as long as the defaults for redirectOutput aren’t modified.
Value | Where output is displayed |
---|---|
«internalConsole» | VS Code debug console. If redirectOutput is set to False, no output is displayed. |
«integratedTerminal» (default) | VS Code Integrated Terminal. If redirectOutput is set to True, output is also displayed in the debug console. |
«externalTerminal» | Separate console window. If redirectOutput is set to True, output is also displayed in the debug console. |
purpose
autoReload
Allows for the automatic reload of the debugger when changes are made to code after the debugger execution has hit a breakpoint. To enable this feature set <"enable": true>as shown in the following code.
*Note: When the debugger performs a reload, code that runs on import might be executed again. To avoid this situation, try to only use imports, constants, and definitions in your module, placing all code into functions. Alternatively, you can also use if __name__==»__main__» checks.
subProcess
redirectOutput
When set to true (the default for internalConsole), causes the debugger to print all output from the program into the VS Code debug output window. If set to false (the default for integratedTerminal and externalTerminal), program output is not displayed in the debugger output window.
This option is typically disabled when using «console»: «integratedTerminal» or «console»: «externalTerminal» because there’s no need to duplicate the output in the debug console.
justMyCode
When omitted or set to true (the default), restricts debugging to user-written code only. Set to false to also enable debugging of standard library functions.
django
pyramid
Sets optional environment variables for the debugger process beyond system environment variables, which the debugger always inherits. The values for these variables must be entered as strings.
envFile
gevent
jinja
Breakpoints and logpoints
Conditional breakpoints
Breakpoints can also be set to trigger based on expressions, hit counts, or a combination of both. The Python extension supports hit counts that are integers, in addition to integers preceded by the ==, >, >=, >5 For more information, see conditional breakpoints in the main VS Code debugging article.
Invoking a breakpoint in code
In your Python code, you can call debugpy.breakpoint() at any point where you want to pause the debugger during a debugging session.
Breakpoint validation
The Python extension automatically detects breakpoints that are set on non-executable lines, such as pass statements or the middle of a multiline statement. In such cases, running the debugger moves the breakpoint to the nearest valid line to ensure that code execution stops at that point.
Debugging specific app types
The configuration dropdown provides various different options for general app types:
Specific steps are also needed for remote debugging and Google App Engine. For details on debugging tests, see Testing.
Flask debugging
The «jinja»: true setting also enables debugging for Flask’s default Jinja templating engine.
If you want to run Flask’s development server in development mode, use the following configuration:
Troubleshooting
There are many reasons why the debugger may not work. Sometimes the debug console reveals specific causes, but the main reasons are as follows:
The path to the python executable is incorrect: check the path of your selected interpreter by running the Python: Select Interpreter command and looking at the current value:
There are invalid expressions in the watch window: clear all expressions from the Watch window and restart the debugger.
If you’re working with a multi-threaded app that uses native thread APIs (such as the Win32 CreateThread function rather than the Python threading APIs), it’s presently necessary to include the following source code at the top of whichever file you want to debug:
If you are working with a Linux system, you may receive a «timed out» error message when trying to apply a debugger to any running process. To prevent this, you can temporarily run the following command:
Debugging
One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.
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, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace 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 best for you.
Start debugging
The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.
It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.
Run and Debug view
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.
Run menu
The top-level Run menu has the most common run and debug commands:
Launch configurations
To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.
To create a launch.json file, click the create a launch.json file link in the Run start view.
VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:
Here is the launch configuration generated for Node.js debugging:
Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.
Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.
Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.
Review all automatically generated values and make sure that they make sense for your project and debugging environment.
Launch versus attach configurations
In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.
If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’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 mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.
VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.
Add a new configuration
VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.
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 want to debug.
As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):
In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.
Debug actions
Once a debug session starts, the Debug toolbar will appear on the top of the editor.
Run mode
In addition to debugging a program, 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’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.
Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.
Breakpoints
Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.
If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.
The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.
Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :
Logpoints
A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.
A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.
Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.
Data inspection
Variables can be 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 CALL STACK section.
Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.
Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.
Variable names and values can be filtered by typing while the focus is on the VARIABLES section.
Launch.json attributes
There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.
The following attributes are mandatory for every launch configuration:
Here are some optional attributes available to all launch configurations:
Many debuggers support some of the following attributes:
Variable substitution
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:
Valid operating properties are «windows» for Windows, «linux» for Linux, and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.
Please note that the type property cannot be 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 program always stops on entry except on macOS:
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:
Advanced breakpoint topics
Conditional breakpoints
A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.
You can add a condition and/or hit 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:
Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.
An example of condition editing in the BREAKPOINTS view:
If a debugger does not 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 column 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 can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.
Function breakpoints
Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function 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 get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.
Debug Console REPL
Note: You must be in a running debug session to use the Debug Console REPL.
Redirect input/output to/from the debug target
Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.
Here are two approaches you might want to consider:
Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as 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 «attach» debug configuration that attaches to the debug target.
If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, » «) as arguments.
Here’s an example launch.json configuration:
This approach requires that the » preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.
Compound launch configurations are displayed in the launch configuration dropdown menu.
Remote debugging
VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.
There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.
Automatically open a URI when debugging a server program
Developing a 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 feature «serverReadyAction» to automate this task.
Here is an example of a simple Node.js Express application:
This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.
The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:
Here the pattern property 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 as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.
The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.
The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.
Trigger Debugging via Edge or Chrome
To simplify things a bit, most properties are optional and we use the following fallback values:
Triggering an Arbitrary Launch Config
In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.
Here the serverReadyAction feature in action:
Next steps
To learn about VS Code’s Node.js debugging support, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about debugging support for other programming languages via VS Code extensions:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
Debugging
One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.
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, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace 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 best for you.
Start debugging
The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.
It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.
Run and Debug view
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.
Run menu
The top-level Run menu has the most common run and debug commands:
Launch configurations
To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.
To create a launch.json file, click the create a launch.json file link in the Run start view.
VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:
Here is the launch configuration generated for Node.js debugging:
Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.
Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.
Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.
Review all automatically generated values and make sure that they make sense for your project and debugging environment.
Launch versus attach configurations
In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.
If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’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 mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.
VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.
Add a new configuration
VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.
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 want to debug.
As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):
In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.
Debug actions
Once a debug session starts, the Debug toolbar will appear on the top of the editor.
Run mode
In addition to debugging a program, 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’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.
Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.
Breakpoints
Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.
If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.
The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.
Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :
Logpoints
A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.
A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.
Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.
Data inspection
Variables can be 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 CALL STACK section.
Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.
Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.
Variable names and values can be filtered by typing while the focus is on the VARIABLES section.
Launch.json attributes
There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.
The following attributes are mandatory for every launch configuration:
Here are some optional attributes available to all launch configurations:
Many debuggers support some of the following attributes:
Variable substitution
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:
Valid operating properties are «windows» for Windows, «linux» for Linux, and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.
Please note that the type property cannot be 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 program always stops on entry except on macOS:
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:
Advanced breakpoint topics
Conditional breakpoints
A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.
You can add a condition and/or hit 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:
Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.
An example of condition editing in the BREAKPOINTS view:
If a debugger does not 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 column 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 can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.
Function breakpoints
Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function 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 get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.
Debug Console REPL
Note: You must be in a running debug session to use the Debug Console REPL.
Redirect input/output to/from the debug target
Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.
Here are two approaches you might want to consider:
Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as 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 «attach» debug configuration that attaches to the debug target.
If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, » «) as arguments.
Here’s an example launch.json configuration:
This approach requires that the » preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.
Compound launch configurations are displayed in the launch configuration dropdown menu.
Remote debugging
VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.
There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.
Automatically open a URI when debugging a server program
Developing a 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 feature «serverReadyAction» to automate this task.
Here is an example of a simple Node.js Express application:
This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.
The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:
Here the pattern property 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 as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.
The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.
The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.
Trigger Debugging via Edge or Chrome
To simplify things a bit, most properties are optional and we use the following fallback values:
Triggering an Arbitrary Launch Config
In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.
Here the serverReadyAction feature in action:
Next steps
To learn about VS Code’s Node.js debugging support, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about debugging support for other programming languages via VS Code extensions:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
Launch json vs code
One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.
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, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace 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 best for you.
The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.
It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.
Run and Debug view
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.
The top-level Run menu has the most common run and debug commands:
To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press kb(workbench.action.debug.start) and VS Code will try to run your currently active file.
To create a launch.json file, click the create a launch.json file link in the Run start view.
VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:
Here is the launch configuration generated for Node.js debugging:
Note : You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.
Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( kb(editor.action.triggerSuggest) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.
Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.
Review all automatically generated values and make sure that they make sense for your project and debugging environment.
Launch versus attach configurations
In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.
If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’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 mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.
VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.
Add a new configuration
VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.
Alternatively, you can run your configuration through the Command Palette ( kb(workbench.action.showCommands) ) by filtering on Debug: Select and Start Debugging or typing ‘debug ‘ and selecting the configuration you want to debug.
As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):
In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.
Once a debug session starts, the Debug toolbar will appear on the top of the editor.
In addition to debugging a program, VS Code supports running the program. The Debug: Run (Start Without Debugging) action is triggered with kb(workbench.action.debug.run) and uses the currently selected launch configuration. Many of the launch configuration attributes are supported in ‘Run’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.
Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.
Breakpoints can be toggled by clicking on the editor margin or using kb(editor.debug.action.toggleBreakpoint) on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.
If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.
The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.
Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :
A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.
A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.
Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.
Variables can be 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 CALL STACK section.
Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.
Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.
Variable names and values can be filtered by typing while the focus is on the VARIABLES section.
There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( kb(editor.action.triggerSuggest) ) to see the list of available attributes once you have specified a value for the type attribute.
The following attributes are mandatory for every launch configuration:
Here are some optional attributes available to all launch configurations:
Many debuggers support some of the following attributes:
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:
Valid operating properties are «windows» for Windows, «linux» for Linux, and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.
Please note that the type property cannot be 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 program always stops on entry except on macOS:
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:
Advanced breakpoint topics
A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.
You can add a condition and/or hit 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:
Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.
An example of condition editing in the BREAKPOINTS view:
If a debugger does not support conditional breakpoints, the Add Conditional Breakpoint and Edit Condition actions will be missing.
Inline breakpoints will only be hit when the execution reaches the column 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 kb(editor.debug.action.toggleInlineBreakpoint) or through the context menu during a debug session. Inline breakpoints are shown inline in the editor.
Inline breakpoints can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.
Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function 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.
If a debugger supports data breakpoints, they can be set from the VARIABLES view and will get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.
Debug Console REPL
Note: You must be in a running debug session to use the Debug Console REPL.
Redirect input/output to/from the debug target
Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.
Here are two approaches you might want to consider:
Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as 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 «attach» debug configuration that attaches to the debug target.
If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, » «) as arguments.
Here’s an example launch.json configuration:
This approach requires that the «
For complex scenarios involving more than one process (for example, a client and a server), VS Code supports multi-target debugging.
Using multi-target debugging is simple: after you’ve started a first debug session, you can just launch another session. As soon as a second session is up and running, the VS Code UI switches to multi-target mode:
Compound launch configurations
An alternative way to start multiple debug sessions is by using a compound launch configuration. A compound launch configuration lists the names of two or more launch configurations that should be launched in parallel. Optionally a preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.
Compound launch configurations are displayed in the launch configuration dropdown menu.
VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.
There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.
Automatically open a URI when debugging a server program
Developing a 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 feature «serverReadyAction» to automate this task.
Here is an example of a simple Node.js Express application:
This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.
The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:
Here the pattern property 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 as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.
The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.
The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.
Trigger Debugging via Edge or Chrome
To simplify things a bit, most properties are optional and we use the following fallback values:
Triggering an Arbitrary Launch Config
In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.
Here the serverReadyAction feature in action:
To learn about VS Code’s Node.js debugging support, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about debugging support for other programming languages via VS Code extensions:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
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 by VS Code extensions available in the Marketplace.
I do not see any launch configurations in the Run and Debug view dropdown. What is wrong?
VS Code | Build, Run and Debug in C++
In this article, we will discuss the VS Code setup required for break-point debugging. Firstly create a file launch.json that configures the VS Code to launch the GDB debugger at the beginning of the debugging process. Then create a file tasks.json that tells VS Code how to build (compile) the program. Finally, make some changes to the console settings and implements the build and debugging.
Program:
Let below be the code for the demonstrate purposes:
Launch.json
This file pertains to information like the name of the debugger, path to the debugger, current CPP file’s directory, and console regarding data. Below is the code in the file launch.json:
Important terms in launch.json: You can either use entirely code given above or otherwise you may use the code generated in your machine automatically. In both cases, you have to take some precautions. Firstly, make sure that the attribute “externalConsole” is marked as true (we will understand its significance later in this topic). Then check whether the property “miDebuggerPath” points to the gdb debugger correctly. Let us discuss these attributes in detail:
Tasks.json:
This file contains information like the commands used for compilation, the compiler’s address, the same label as in launch.json, and some other information. Below is the code in the file task.json:
Important terms in task.json: The above mentioned tasks.json file can be used entirely without caution. However, the only thing to take care of is that the label of tasks.json should match with preLaunchTask of Launch.json. Let’s discuss some terms in more detail:
Steps:
Running and debugging Java
Visual Studio Code allows you to debug Java applications through the Debugger for Java extension. It’s a lightweight Java debugger based on Java Debug Server, which extends the Language Support for Java™ by Red Hat.
Here’s a list of supported debugging features:
The Java debugger is an open-source project, which welcomes contributors to collaborate through GitHub repositories:
If you run into any issues when using the features below, you can contact us by entering an issue.
Install
To get the complete Java language support in Visual Studio Code, you can install the Extension Pack for Java, which includes the Debugger for Java extension.
For details on how to get started with the extension pack, you can review the Getting Started with Java tutorial.
Configure
By default, the debugger will run out-of-box by automatically finding the main class and generating a default launch configuration in memory to launch your application.
If you would like to customize and persist your launch configuration, you can select the create a launch.json file link in the Run and Debug view.
Run and Debug
The debugger extension provides multiple ways to run and debug your Java application.
Run from CodeLens
You will find Run|Debug on the CodeLens of your main() function.
Run from Editor menu
Another way to start debugging is to select Run Java or Debug Java menu from the top editor title bar.
Run from pressing F5
Debugging single files
In addition to support for debugging Java projects managed by build tools, VS Code also supports for debugging single Java files without any project.
Debug session inputs
The default Debug Console in VS Code doesn’t support inputs. If your program need inputs from a terminal, you can use the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) within VS Code or an external terminal to launch it. You can also use the user setting java.debug.settings.console to configure a global console for all Java debug sessions.
Breakpoints
The Debugger for Java supports various breakpoints, such as line breakpoints, conditional breakpoints, data breakpoints, logpoints.
With the help of expression evaluation, the debugger also supports conditional breakpoint. You can set your breakpoint to break when expression evaluates to true.
You can have the debugger break when a variable changes its value. Note that the data breakpoint can only be set inside a debug session. This means you need to launch your application and break on a regular breakpoint first. You can then pick a field in the VARIABLES view and set a data breakpoint.
Logpoints is also supported by Java Debugger. Logpoints allow you to send output to Debug Console without editing code. They’re different from breakpoints because they don’t stop the execution flow of your application.
Expression evaluation
The debugger also lets you evaluate expressions in the WATCH window as well as the Debug Console.
Hot Code Replace
Another advanced feature the debugger supports is ‘Hot Code’ replacement. Hot Code Replace (HCR) is a debugging technique whereby the Debugger for Java transmits the class changes over the debugging channel to another Java Virtual Machine (JVM). HCR facilitates experimental development and fosters iterative trial-and-error coding. With this new feature, you can start a debugging session and change a Java file in your development environment, and the debugger will replace the code in the running JVM. No restart is required, which is why it’s called «hot». Below is an illustration of how you can use HCR with Debugger for Java in VS Code.
You may use the debug setting java.debug.settings.hotCodeReplace to control how to trigger Hot Code Replace. The possible setting values are:
Step filtering
Step filter is supported by the extension to filter out types that you do not want to see or step through while debugging. With this feature, you can configure the packages to filter within your launch.json so they could be skipped when you step through.
Configuration options
There are many options and settings available to configure the debugger. For example, configuring the JVM arguments and environment variables is easily done with launch options.
Consult the documentation for the Language Support for Java™ by Red Hat extension for help with setting up your project.
For many commonly used setups, there are samples available in VS Code Java Debugger Configuration. The document explains how the Java debugger automatically generates configurations for you, and if you need to modify them, how to do so with Main class, different arguments, environment, attaching to other Java processes, and usage of more advanced features.
Launch
Attach
User settings
Troubleshooting
If you encounter issues when using the debugger, a detailed troubleshooting guide can be found in the vscode-java-debug GitHub repository.
Common issues explained include:
Feedback and questions
You can find the full list of issues at the vscode-java-debug repository. You can submit a bug or feature suggestion and participate in the community driven vscode-java-debug Gitter channel.
Next steps
Read on to find out about:
Launch json vs code
Java Debug Configuration
The debugger provides two kinds of configuration: launch.json and settings.json (User Settings), see the README for the supported configuration list. launch.json is used to control the configuration per debug session, and the user setting is shared by the whole workspace or VS Code.
Auto generate the launch.json
When you run the program via Run|Debug CodeLens or Run / Debug context menu, the debugger automatically generates the launching configuration for you.
Modify the launch.json
On the other hand, the debugger provides multiple configuration templates to help you to easily add a new configuration. When you type «java» or «» in launch.json, it will trigger auto-completion suggestions.
In case you want to manually edit the configuration, below are the explanation and samples about the common debug configurations.
«mainClass»: «»
If you have no idea about what to set here, just leave it empty. The debugger will search all possible main classes from the workspace, then prompt you the list to choose for launch.
«mainClass»: «$
If you have multiple main Java files, use this to auto switch to your current focus program. The debugger will resolve the main class from current active Java file, and set it as the launching main class.
«mainClass»: «com.microsoft.app.myApp»
The fully qualified class name, generally it’s filled by the debugger’s auto generation.
Pro Tip: The easiest way to get the project name is to install Java Dependency Viewer extension, the top node in the JAVA DEPENDENCIES view is your project name.
«args»: «arg0 arg1»
Space separated String value.
«args»: [«arg0», «arg1»]
An array of String.
«args»: «$
The debugger will prompt you with an input box to type the args value before launching the program. This is convenient when you have a program running against multiple data set.
«console»: «internalConsole»
VS Code debug console (input stream not supported). If you’re developing backend application, internalConsole is recommended.
«console»: «integratedTerminal»
VS Code integrated terminal. If you’re developing console application with io input requirements, you must use the terminal to accept user input. For example, use Scanner class for user input.
«console»: «externalTerminal»
External terminal that can be configured in user settings. The user scenario is same as integrated terminal. The difference is opening an external terminal window to run your program.
Don’t step into the specified classes or methods
Skip the class loader.
Skip the JDK classes.
Skip the constructors and the synthetic methods.
Attach to a debuggee
In some cases, you may want to start your program with the external builder and launcher, then you can configure these jobs in tasks.json and attach to it. For example, launching springboot application via mvn command, and then attach a debugger.
Attach to mvn task
Attach to embedded maven tomcat server
If you want to try to debug your Java webapps in a standalone tomcat server, please try VS Code Tomcat for Java extension.
If you want to try to debug embedded tomcat server with gradle plugin, see the gradle sample.
Use javac as the builder and attach to java process
Modify the settings.json (User Setting)
1. No way to take input.
2. Code output is not in the DEBUG CONSOLE panel but Terminal.
3. The classpath changed when using terminal.
4. Failed to launch debuggee in terminal with TransportTimeoutException.
Настройка задач сборки и отладки для режима разработки «Открытая папка»
Visual Studio поддерживает множество разных языков и баз кода, но не все существующие варианты. Если вы откроете в Visual Studio папку с кодом, который поддерживает Visual Studio, его можно выполнить немедленно и без дополнительных настроек.
Если в базе кода используются пользовательские средства сборки, которые не распознаются Visual Studio, для выполнения и отладки такого кода в Visual Studio требуются определенные сведения о конфигурации. Чтобы указать Visual Studio правила сборки вашего кода, определите задачи сборки. Создав одну или несколько задач сборки, вы сможете указать в них все элементы, которые потребуются для сборки и выполнения кода на определенном языке. Кроме того, можно создавать произвольные задачи с практически неограниченными возможностями. Например, с помощью задач можно вывести список содержимого папки или переименовать файл.
Чтобы настроить базу кода, не относящуюся к конкретному проекту, воспользуйтесь следующими файлами .json:
Имя файла | Цель |
---|---|
tasks.vs.json | Определяет настраиваемые команды сборки и параметры компилятора, а также произвольные (не имеющие отношения к сборке) задачи. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Настройка задач. |
launch.vs.json | Определяет аргументы командной строки для отладки. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Параметры отладки и запуска. |
Описанные файлы .json находятся в скрытой папке с именем .vs в корневой папке базы кода. Файлы tasks.vs.json и launch.vs.json создаются в среде Visual Studio по мере необходимости, то есть когда вы выбираете в обозревателе решений действия Настройка задач или Параметры отладки и запуска для файла или папки. Эти файлы .json скрыты, потому что пользователи обычно не добавляют их в систему управления версиями. Но если требуется возможность записать их в систему управления версиями, с помощью файловой системы перетащите файлы в корневую папку базы кода, где они будут видны в Обозревателе решений и в системе управления версиями.
Чтобы просмотреть скрытые папки в Visual Studio, нажмите кнопку Показать все файлы на панели инструментов обозревателя решений.
Определение задач в файле tasks.vs.json
Вы можете автоматизировать скрипты сборки и любые внешние операции с файлами, размещенными в текущей рабочей области, запуская их как задачи в интегрированной среде разработки. Чтобы настроить новую задачу, щелкните правой кнопкой мыши нужный файл или папку и выберите Настройка задач.
В среде разработки откроется (или будет создан, если его еще нет) файл tasks.vs.json в папке .vs. Можно определить в этом файле задачу сборки или произвольную задачу, а затем вызывать ее по имени в контекстном меню обозревателя решений.
Настраиваемые задачи можно размещать в отдельных файлах или во всех файлах определенного типа. Например, можно определить во всех файлах пакета NuGet задачу «Восстановить пакеты» или поместить во все файлы исходного кода задачу статического анализа, например анализатор кода для всех JS-файлов.
Определение настраиваемых задач сборки
Если в базе кода используются настраиваемые средства сборки, которые не распознаются в Visual Studio, вам не удастся выполнить и отладить код в Visual Studio без нескольких дополнительных настроек. Visual Studio поддерживает задачи сборки, в которых вы можете указать Visual Studio правила сборки, перестроения и очистки кода. Файл задачи сборки tasks.vs.json связывает внутренний цикл разработки Visual Studio с пользовательскими средствами сборки, применяемыми для базы кода.
Давайте рассмотрим пример базы кода, которая состоит из одного файла на языке C# с именем hello.cs. Файл makefile для такой базы кода может выглядеть следующим образом:
Этот файл makefile содержит целевые объекты сборки, очистки и перестроения, и вы можете определить для него указанный ниже файл tasks.vs.json. Он содержит три задачи сборки (для сборки, перестроения и очистки), для которых применяется средство сборки NMAKE.
Когда вы определите в файле tasks.vs.json задачи сборки, в контекстном меню обозревателя решений для соответствующих файлов появятся дополнительные пункты. В нашем примере для всех файлов makefile в контекстное меню добавляются действия «Сборка», «Перестроить» и «Очистить».
Если вы выберете любой из этих вариантов, будет выполнена соответствующая задача. Выходные данные отображаются в окне Вывод, а ошибки сборки — в окне Список ошибок.
Определение произвольных задач
Вы можете описать в файле tasks.vs.json произвольную задачу, которая предназначена для выполнения любого действия. Например, можно определить задачу для отображения имени файла, выбранного в окне вывода, или списка файлов в указанном каталоге.
Ниже представлен пример файла tasks.vs.json, который определяет одну задачу. При вызове этой задачи отображается имя выбранного файла .js.
Сохранив файл tasks.vs.json, вы можете щелкнуть правой кнопкой мыши любой файл .js и выбрать команду Echo filename (Отобразить имя файла). Имя файла будет отображено в окне Вывод.
Если в базе кода нет файлов tasks.vs.json, вы можете создать такой файл с помощью команды Настройка задач в контекстном меню обозревателя решений. Эту команду также можно вызвать, щелкнув файл правой кнопки мыши.
В следующем примере определяется задача перечисления всех файлов и вложенных папок из каталога bin.
Эта задача применяется ко всем файлам. Открыв в обозревателе решений контекстное меню для любого файла, вы увидите в нижней части этого меню задачу с именем List Outputs (Перечислить выходные объекты). Если выбрать команду List Outputs (Перечислить выходные объекты), все содержимое каталога bin выводится в окне Вывод в Visual Studio.
Область действия параметров
В корневой папке и вложенных папках базы кода может быть несколько файлов tasks.vs.json. Такой подход позволяет гибко настраивать разные правила для разных каталогов в базе кода. Visual Studio объединяет или переопределяет параметры для разных разделов базы кода, используя следующий приоритет файлов:
Эти правила агрегирования применяются к tasks.vs.json. Сведения о правилах агрегирования параметров для другого файла см. в посвященном ему разделе этой статьи.
Свойства для tasks.vs.json
В этом разделе описаны некоторые свойства, которые можно задать в файле tasks.vs.json.
appliesTo
Маска файла | Описание |
---|---|
«*» | Задача доступна для всех файлов и папок в рабочей области. |
«*/» | Задача доступна для всех папок в рабочей области. |
«*.js» | Задача доступна для всех файлов с расширением JS в рабочей области. |
«/*.js» | Задача доступна для всех файлов с расширением JS в корневой папке рабочей области. |
«src/*/» | Задача доступна для всех подпапок в папке SRC. |
«makefile» | Задача доступна для всех файлов makefile в рабочей области. |
«/makefile» | Задача доступна только для файлов makefile в корневой папке рабочей области. |
Макросы для tasks.vs.json
Настройка отладки с помощью launch.vs.json
Сведения о настройке проектов CMake для отладки см. в разделе Настройка сеансов отладки CMake.
Чтобы настроить отладку для базы кода, выберите в контекстном меню обозревателя решений пункт Параметры отладки и запуска. Также его можно открыть, щелкнув исполняемый файл правой кнопкой мыши.
В диалоговом окне Выбор отладчика выберите нужный вариант и нажмите кнопку Выбрать.
Если файла launch.vs.json еще нет, он будет автоматически создан.
Теперь щелкните правой кнопкой мыши исполняемый файл в обозревателе решений и выберите команду Назначить автозапускаемым элементом.
Теперь этот исполняемый файл будет отмечен как автозапускаемый элемент и его имя отобразится на кнопке Пуск на панели инструментов отладки.
Нажатие клавиши F5 запускает отладчик, который будет останавливаться на всех заданных точках останова. Все обычные окна отладчика будут доступны и активны.
Дополнительные сведения о настраиваемых задачах сборки и отладки в проектах открытых папок C++ см. в статье Open Folder support for C++ build systems in Visual Studio (Поддержка открытых папок для систем сборки C++ в Visual Studio).
Указание аргументов для отладки
Когда вы сохраните этот файл, имя новой конфигурации отобразится в раскрывающемся списке для целевого объекта отладки. Вы можете выбрать ее, чтобы запустить отладчик. Можно создать любое количество конфигураций отладки.
Дополнительные файлы параметров
Помимо трех файлов .json, которые описаны в этом разделе, Visual Studio считывает параметры из нескольких дополнительных файлов, если обнаружит их в базе кода.
.vscode\settings.json
Вы можете определить в базе кода любое количество файлов .vscode\settings.json. Параметры из этого файла применяются к каталогу на один уровень выше соответствующего .vscode и ко всем его подкаталогам.
.gitignore
Файлы .gitignore позволяют указать Git, что некоторые файлы следует игнорировать. Здесь вы перечисляете файлы и каталоги, которые не нужно регистрировать в репозитории. Файлы .gitignore обычно включаются в базу кода, чтобы все разработчики базы кода могли использовать эти параметры. Visual Studio считывает шаблоны из файлов .gitignore для фильтрации элементов при отображении и в некоторых средствах поиска.
Параметры из файла .gitignore применяются к родительскому каталогу файла и всем его подкаталогам.
Configure VS Code for Microsoft C++
In this tutorial, you configure Visual Studio Code to use the Microsoft Visual C++ compiler and debugger on Windows.
After configuring VS Code, you will compile and debug a simple Hello World program in VS Code. This tutorial does not teach you details about the Microsoft C++ toolset or the C++ language. For those subjects, there are many good resources available on the Web.
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
To successfully complete this tutorial, you must do the following:
Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘c++’ in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
Install the Microsoft Visual C++ (MSVC) compiler toolset.
If you have a recent version of Visual Studio, open the Visual Studio Installer from the Windows Start menu and verify that the C++ workload is checked. If it’s not installed, then check the box and select the Modify button in the installer.
You can also install the Desktop development with C++ workload without a full Visual Studio IDE installation. From the Visual Studio Downloads page, scroll down until you see Tools for Visual Studio 2022 under the All Downloads section and select the download for Build Tools for Visual Studio 2022.
This will launch the Visual Studio Installer, which will bring up a dialog showing the available Visual Studio Build Tools workloads. Check the Desktop development with C++ workload and select Install.
Note: You can use the C++ toolset from Visual Studio Build Tools along with Visual Studio Code to compile, build, and verify any C++ codebase as long as you also have a valid Visual Studio license (either Community, Pro, or Enterprise) that you are actively using to develop that C++ codebase.
Check your Microsoft Visual C++ installation
To use MSVC from a command line or VS Code, you must run from a Developer Command Prompt for Visual Studio. An ordinary shell such as PowerShell, Bash, or the Windows command prompt does not have the necessary path environment variables set.
To open the Developer Command Prompt for VS, start typing ‘developer’ in the Windows Start menu, and you should see it appear in the list of suggestions. The exact name depends on which version of Visual Studio or the Visual Studio Build Tools you have installed. Select the item to open the prompt.
If the Developer Command Prompt is using the BuildTools location as the starting directory (you wouldn’t want to put projects there), navigate to your user folder ( C:\users\
Note: If for some reason you can’t run VS Code from a Developer Command Prompt, you can find a workaround for building C++ projects with VS Code in Run VS Code outside a Developer Command Prompt.
Create Hello World
Add a source code file
Add hello world source code
Now paste in this source code:
Now press ⌘S (Windows, Linux Ctrl+S ) to save the file. Notice how the file you just added appears in the File Explorer view ( ⇧⌘E (Windows, Linux Ctrl+Shift+E ) ) in the side bar of VS Code:
You can also enable Auto Save to automatically save your file changes, by checking Auto Save in the main File menu.
The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. You can find out more about the other views in the VS Code User Interface documentation.
Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).
Explore IntelliSense
In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:
You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.
Run helloworld.cpp
Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have a C++ compiler installed before attempting to run and debug helloworld.cpp in VS Code.
Open helloworld.cpp so that it is the active file.
Press the play button in the top right corner of the editor.
Choose C/C++: cl.exe build and debug active file from the list of detected compilers on your system.
After the build succeeds, your program’s output will appear in the integrated Terminal.
Your new tasks.json file should look similar to the JSON below:
Note: You can learn more about tasks.json variables in the variables reference.
The command setting specifies the program to run; in this case that is «cl.exe». The args array specifies the command-line arguments that will be passed to cl.exe. These arguments must be specified in the order expected by the compiler.
The label value is what you will see in the tasks list; you can name this whatever you like.
The detail value is what you will as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.
Modifying tasks.json
Debug helloworld.cpp
Explore the debugger
Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:
The Integrated Terminal appears at the bottom of the source code editor. In the Debug Output tab, you see output that indicates the debugger is up and running.
The editor highlights the line where you set a breakpoint before starting the debugger:
The Run and Debug view on the left shows debugging information. You’ll see an example later in the tutorial.
At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.
Step through the code
Now you’re ready to start stepping through the code.
Click or press the Step over icon in the debugging control panel.
This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.
In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.
Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.
Press Step over again to execute the cout statement. (Note that as of the March 2019 release, the C++ extension does not print any output to the Debug Console until the loop exits.)
If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!
Set a watch
Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.
To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.
Customize debugging with launch.json
There are cases where you’d want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json file.
You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: cl.exe build and debug active file.
VS Code creates a launch.json file, which looks something like this:
Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.
From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.
C/C++ configurations
If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.
You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path.
Compiler path
The compilerPath setting is an important setting in your configuration. The extension uses it to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide useful features like smart completions and Go to Definition navigation.
The C/C++ extension attempts to populate compilerPath with the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.
The compilerPath search order is:
If you have g++ or WSL installed, you might need to change compilerPath to match the preferred compiler for your project. For Microsoft C++, the path should look something like this, depending on which specific version you have installed: «C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Tools/MSVC/14.16.27023/bin/Hostx64/x64/cl.exe».
Reusing your C++ configuration
Run VS Code outside the Developer Command Prompt
In certain circumstances, it isn’t possible to run VS Code from Developer Command Prompt for Visual Studio (for example, in Remote Development through SSH scenarios). In that case, you can automate initialization of Developer Command Prompt for Visual Studio during the build using the following tasks.json configuration:
Troubleshooting
The term ‘cl.exe’ is not recognized
If you see the error «The term ‘cl.exe’ is not recognized as the name of a cmdlet, function, script file, or operable program.», this usually means you are running VS Code outside of a Developer Command Prompt for Visual Studio and VS Code doesn’t know the path to the cl.exe compiler.
VS Code must either be started from the Developer Command Prompt for Visual Studio, or the task must be configured to run outside a Developer Command Prompt.
Launch json vs code
Configuring launch.json for C# debugging
The launch.json file is used to configure the debugger in Visual Studio Code.
If you have more than one launchable project, then you will need to modify your launch.json file by hand. Visual Studio Code will still generate a basic template, but you will need to fill in the ‘program’ field to point at the executable dll that you would like to debug.
Configurating VS Code’s debugging behavior
The preLaunchTask field runs the associated taskName in tasks.json before debugging your program. You can get the default build prelaunch task by executing the command Tasks: Configure Tasks Runner from the VS Code command palette.
This property normally takes the form: «$
is the name of debugged project’s build output dll. This is normally the same as the project file name but with a ‘.dll’ extension.
The working directory of the target process.
These are the arguments that will be passed to your program.
If you need to stop at the entry point of the target, you can optionally set stopAtEntry to be «true».
Starting a Web Browser
The default launch.json template (as of C# extension v1.20.0) for ASP.NET Core projects will use the following to configure VS Code to launch a web browser when ASP.NET starts:
Specifying the browser’s URL
If you want to ignore the URL from the console output, you can remove the ( and ) from the pattern, and the set uriFormat to what you want to launch. Example:
If you want to use the port number from the console output, but not the host name, you can also use something like this:
In fact, you can open almost any url, for example you could open the default swagger ui by doing something like this:
Note You need to make sure your project has swaggerui setup to do this.
Environment variables may be passed to your program using this schema:
Console (terminal) window
«internalConsole» (default) : the target process’s console output (stdout/stderr) goes to the VS Code Debug Console. This is useful for executables that take their input from the network, files, etc. But this does NOT work for applications that want to read from the console (ex: Console.ReadLine ).
«integratedTerminal» : the target process will run inside VS Code’s integrated terminal. Click the ‘Terminal’ tab in the tab group beneath the editor to interact with your application. Alternatively add «internalConsoleOptions»: «neverOpen» to make it so that the default foreground tab is the terminal tab.
«externalTerminal» : the target process will run inside its own external terminal.
To configure which launchSettings.json profile to use (or to prevent it from being used), set the launchSettingsProfile option:
Which would then, for example, use myVariableName from this example launchSettings.json file:
If launchSettingsProfile is NOT specified, the first profile with «commandName»: «Project» will be used.
If launchSettingsProfile is set to null/an empty string, then Properties/launchSettings.json will be ignored.
By default, the debugger will search for launchSettings.json in
You can optionally configure how source files are opened by providing a map using this form:
You can optionally disable justMyCode by setting it to «false». You should disable Just My Code when you are trying to debug into a library that you pulled down which doesn’t have symbols or is optimized.
Require Exact Source
The debugger requires the pdb and source code to be exactly the same. To change this and disable the sources to be the same add:
Stepping into properties and operators
The debugger steps over properties and operators in managed code by default. In most cases, this provides a better debugging experience. To change this and enable stepping into properties or operators add:
You can optionally enable or disable messages that should be logged to the output window. The flags in the logging field are: ‘exceptions’, ‘moduleLoad’, ‘programOutput’, ‘engineLogging’, and ‘browserStdOut’.
More information about pipe transport can be found here.
You can find information on configuring pipe transport for Windows Subsystem for Linux (WSL) here.
Operating System Specific Configurations
If there specific commands that need to be changed per operating system, you can use the fields: ‘windows’, ‘osx’, or ‘linux’. You can replace any of the fields mentioned above for the specific operating system.
Suppress JIT Optimizations
Normally the Release build configuration creates optimized code and the Debug build configuration does not. The Optimize MSBuild property controls whether the compiler is told to optimize code.
When should you use this option: This option should be used when you have downloaded dlls from another source, such as a nuget package, and you want to debug the code in this DLL. In order for this to work you must also find the symbol (.pdb) file for this DLL.
Limitations of this option: There are two situations where this option will NOT work:
1: In situations where you are attaching the debugger to an already running process, this option will have no effect on modules that were already loaded at the time the debugger was attached.
The symbolOptions element allows customization of how the debugger searches for symbols. Example:
cachePath«: Directory where symbols downloaded from symbol servers should be cached. If unspecified, on Windows the debugger will default to %TEMP%\SymbolCache, and on Linux and macOS the debugger will default to
Properties for «loadAllButExcluded» mode:
moduleFilter.excludedModules: Array of modules that the debugger should NOT load symbols for. Wildcards (example: MyCompany.*.dll) are supported.
Properties for «loadOnlyIncluded» mode:
moduleFilter.includedModules: Array of modules that the debugger should load symbols for. Wildcards (example: MyCompany.*.dll) are supported.
moduleFilter.includeSymbolsNextToModules: If true, for any module NOT in the ‘includedModules’ array, the debugger will still check next to the module itself and the launching executable, but it will not check paths on the symbol search list. This option defaults to ‘true’.
Source Link options
The sourceLinkOptions element in launch.json allows customization of Source Link behavior by URL. It is a map from URL to Source Link options for that URL. Wildcards are supported in the URL name. Currently the only customization is if Source Link is enabled for that URL, but more options may be added in the future.
This example will enable Source Link for GitHub URLs, and disable Source Link for all other URLs.
The default value of this option is to enable Source Link for all URLs. Similarly, Source Link will be enabled for any URL that doesn’t have a rule in the sourceLinkOptions map.
If multiple entries cover the same URL, the more specific entry (the entry with the longer string length) will be used.
Currently Source Link only works for source files that can be accessed without authentication. So, for example, the debugger can download source files from open source projects on GitHub, but it cannot download from private GitHub repos, or from Visual Studio Team Services.
Target Architecture options (macOS M1)
Отладка React-приложений в VS Code
Прошли те дни, когда мне, в процессе разработки, приходилось тратить время, переключаясь между терминалом, браузером и редактором. Теперь всё делается иначе — быстрее и удобнее. Сегодня я расскажу об оптимизации повседневных дел React-разработчика. А именно, речь пойдёт о том, как связать Visual Studio Code и Google Chrome. Это даст возможность отлаживать браузерный код в редакторе.
Средства отладки VS Code и jest от Facebook
Настройка тестового проекта
Прежде чем мы начнём осваивать отладку React в VS Code, создадим учебное приложение, с которым будем экспериментировать. Я часто пользуюсь create-react-app, так как очень не люблю вручную создавать пустые проекты. Поэтому предлагаю задействовать его и в этом руководстве. Как вариант, если у вас уже есть приложение, вы можете воспользоваться им.
Итак, создадим тестовый проект. Для этого надо сделать следующее:
Настройка VS Code
Теперь установим расширение VS Code, которое позволит редактору взаимодействовать с Chrome. VS Code подключается к Chome с использованием протокола удалённой отладки. Это — тот же протокол, который используют инструменты разработчика Chrome. Но, благодаря такому подходу, вместо того, чтобы работать со стандартными инструментами Chrome, вы можете использовать для отладки браузерного кода VS Code.
Установка расширения Debugger for Chrome
Поиск расширения Debugger for Chrome
Подключение VS Code к Chrome
Далее, нужно настроить VS Code на подключение к Chrome. Делается это так:
Настройка связи VS Code и Chrome
Полный список конфигурационных опций можно найти здесь.
Использование отладчика
Теперь почти всё готово к работе. Следующий шаг заключается в использовании тестового проекта для того, чтобы проверить отладчик.
Запуск отладчика
Запустить отладчик можно, выполнив одно из следующих действий:
Панель инструментов, которая появляется при включении отладчика
Установка точки останова
Точки останова используются для того, чтобы сообщить отладчику о том, что ему нужно приостановить выполнение кода в определённом месте. Это позволяет программисту исследовать переменные, стек вызовов и вносить в код изменения в процессе выполнения приложения.
Установка точки останова
Запуск сервера разработки
Перейдите по адресу http://localhost:3000/ и вы увидите, как страница «застынет». Это происходит из-за того, что сработала точка останова. Если перейти в VS Code, можно заметить, что строка 11 будет выделена, а на панели отладки появятся сведения о стеке вызовов.
Сработавшая точка останова
Если у вас всё заработало — примите поздравления! Вы только что узнали о том, как настроить удалённую отладку в VS Code. Если вы хотите узнать подробности о самом процессе отладки в VS Code — почитайте это.
Непрерывное тестирование с помощью jest
Непрерывное тестирование в VS Code
Итоги
В этом материале мы рассказали о том, как настроить взаимодействие VS Code и Chrome для организации удалённой отладки React-приложений. Надеемся, эта простая методика поможет сэкономить немного времени, если раньше вам приходилось постоянно переключаться между редактором, браузером и терминалом.
Уважаемые читатели! Пользуетесь ли вы какими-нибудь полезными мелочами, которые повышают производительность труда при разработке веб-приложений?
Debugging
One of the key features of Visual Studio Code is its great debugging support. VS Code’s built-in debugger helps accelerate your edit, compile, and debug loop.
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, Ruby, Go, C#, Python, C++, PowerShell and many others), look for Debuggers extensions in the VS Code Marketplace 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 best for you.
Start debugging
The following documentation is based on the built-in Node.js debugger, but most of the concepts and features are applicable to other debuggers as well.
It is helpful to first create a sample Node.js application before reading about debugging. You can follow the Node.js walkthrough to install Node.js and create a simple «Hello World» JavaScript application ( app.js ). Once you have a simple application set up, this page will take you through VS Code debugging features.
Run and Debug view
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.
Run menu
The top-level Run menu has the most common run and debug commands:
Launch configurations
To run or debug a simple app in VS Code, select Run and Debug on the Debug start view or press F5 and VS Code will try to run your currently active file.
To create a launch.json file, click the create a launch.json file link in the Run start view.
VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:
Here is the launch configuration generated for Node.js debugging:
Note: You can debug a simple application even if you don’t have a folder open in VS Code, but it is not possible to manage launch configurations and set up advanced debugging. The VS Code Status Bar is purple if you do not have a folder open.
Note that the attributes available in launch configurations vary from debugger to debugger. You can use IntelliSense suggestions ( ⌃Space (Windows, Linux Ctrl+Space ) ) to find out which attributes exist for a specific debugger. Hover help is also available for all attributes.
Do not assume that an attribute that is available for one debugger automatically works for other debuggers too. If you see green squiggles in your launch configuration, hover over them to learn what the problem is and try to fix them before launching a debug session.
Review all automatically generated values and make sure that they make sense for your project and debugging environment.
Launch versus attach configurations
In VS Code, there are two core debugging modes, Launch and Attach, which handle two different workflows and segments of developers. Depending on your workflow, it can be confusing to know what type of configuration is appropriate for your project.
If you come from a browser Developer Tools background, you might not be used to «launching from your tool,» since your browser instance is already open. When you open DevTools, you are simply attaching DevTools to your open browser tab. On the other hand, if you come from a server or desktop background, it’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 mode before VS Code attaches to it, while an attach configuration is a recipe for how to connect VS Code’s debugger to an app or process that’s already running.
VS Code debuggers typically support launching a program in debug mode or attaching to an already running program in debug mode. Depending on the request ( attach or launch ), different attributes are required, and VS Code’s launch.json validation and suggestions should help with that.
Add a new configuration
VS Code also supports compound launch configurations for starting multiple configurations at the same time; for more details, please read this section.
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 want to debug.
As soon as a debugging session starts, the DEBUG CONSOLE panel is displayed and shows debugging output, and the Status Bar changes color (orange for default color themes):
In addition, the debug status appears in the Status Bar showing the active debug configuration. By selecting the debug status, a user can change the active launch configuration and start debugging without needing to open the Run and Debug view.
Debug actions
Once a debug session starts, the Debug toolbar will appear on the top of the editor.
Run mode
In addition to debugging a program, 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’ mode. VS Code maintains a debug session while the program is running, and pressing the Stop button terminates the program.
Tip: The Run action is always available, but not all debugger extensions support ‘Run’. In this case, ‘Run’ will be the same as ‘Debug’.
Breakpoints
Breakpoints can be toggled by clicking on the editor margin or using F9 on the current line. Finer breakpoint control (enable/disable/reapply) can be done in the Run and Debug view’s BREAKPOINTS section.
If the debugger supports breaking on different kinds of errors or exceptions, those will also be available in the BREAKPOINTS view.
The Reapply All Breakpoints command sets all breakpoints again to their original location. This is helpful if your debug environment is «lazy» and «misplaces» breakpoints in source code that has not yet been executed.
Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler :
Logpoints
A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be paused or stopped.
A Logpoint is represented by a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Just like regular breakpoints, Logpoints can be enabled or disabled and can also be controlled by a condition and/or hit count.
Note: Logpoints are supported by VS Code’s built-in Node.js debugger, but can be implemented by other debug extensions. The Python and Java extensions, for example, support Logpoints.
Data inspection
Variables can be 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 CALL STACK section.
Variable values can be modified with the Set Value action from the variable’s context menu. Additionally, you can use the Copy Value action to copy the variable’s value, or Copy as Expression action to copy an expression to access the variable.
Variables and expressions can also be evaluated and watched in the Run and Debug view’s WATCH section.
Variable names and values can be filtered by typing while the focus is on the VARIABLES section.
Launch.json attributes
There are many launch.json attributes to help support different debuggers and debugging scenarios. As mentioned above, you can use IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) to see the list of available attributes once you have specified a value for the type attribute.
The following attributes are mandatory for every launch configuration:
Here are some optional attributes available to all launch configurations:
Many debuggers support some of the following attributes:
Variable substitution
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:
Valid operating properties are «windows» for Windows, «linux» for Linux, and «osx» for macOS. Properties defined in an operating system specific scope override properties defined in the global scope.
Please note that the type property cannot be 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 program always stops on entry except on macOS:
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:
Advanced breakpoint topics
Conditional breakpoints
A powerful VS Code debugging feature is the ability to set conditions based on expressions, hit counts, or a combination of both.
You can add a condition and/or hit 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:
Condition and hit count editing support is also supported for function and exception breakpoints. You can initiate condition editing from the context menu or the new inline Edit Condition action.
An example of condition editing in the BREAKPOINTS view:
If a debugger does not 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 column 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 can also have conditions. Editing multiple breakpoints on a line is possible through the context menu in the editor’s left margin.
Function breakpoints
Instead of placing breakpoints directly in source code, a debugger can support creating breakpoints by specifying a function name. This is useful in situations where source is not available but a function 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 get hit when the value of the underlying variable changes. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.
Debug Console REPL
Note: You must be in a running debug session to use the Debug Console REPL.
Redirect input/output to/from the debug target
Redirecting input/output is debugger/runtime specific, so VS Code does not have a built-in solution that works for all debuggers.
Here are two approaches you might want to consider:
Launch the program to debug («debug target») manually in a terminal or command prompt and redirect input/output as 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 «attach» debug configuration that attaches to the debug target.
If the debugger extension you are using can run the debug target in VS Code’s Integrated Terminal (or an external terminal), you can try to pass the shell redirect syntax (for example, » «) as arguments.
Here’s an example launch.json configuration:
This approach requires that the » preLaunchTask can be specified that is run before the individual debug sessions are started. The boolean flag stopAll controls whether manually terminating one session will stop all of the compound sessions.
Compound launch configurations are displayed in the launch configuration dropdown menu.
Remote debugging
VS Code does not itself support remote debugging: this is a feature of the debug extension you are using, and you should consult the extension’s page in the Marketplace for support and details.
There is, however, one exception: the Node.js debugger included in VS Code supports remote debugging. See the Node.js Debugging topic to learn how to configure this.
Automatically open a URI when debugging a server program
Developing a 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 feature «serverReadyAction» to automate this task.
Here is an example of a simple Node.js Express application:
This application first installs a «Hello World» handler for the «/» URL and then starts to listen for HTTP connections on port 3000. The port is announced in the Debug Console, and typically, the developer would now type http://localhost:3000 into their browser application.
The serverReadyAction feature makes it possible to add a structured property serverReadyAction to any launch config and select an «action» to be performed:
Here the pattern property 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 as a regular expression capture group. In this example, we are extracting only the port number, but it is also possible to extract a full URI.
The uriFormat property describes how the port number is turned into a URI. The first %s is substituted by the first capture group of the matching pattern.
The resulting URI is then opened outside of VS Code («externally») with the standard application configured for the URI’s scheme.
Trigger Debugging via Edge or Chrome
To simplify things a bit, most properties are optional and we use the following fallback values:
Triggering an Arbitrary Launch Config
In some cases, you may need to configure additional options for the browser debug session—or use a different debugger entirely. You can do this by setting action to startDebugging with a name property set to the name of the launch configuration to start when the pattern is matched.
Here the serverReadyAction feature in action:
Next steps
To learn about VS Code’s Node.js debugging support, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about debugging support for other programming languages via VS Code extensions:
To learn about VS Code’s task running support, go to:
To write your own debugger extension, visit:
- Last pirates code
- Launcher minecraft closed with exit code 1