preface

VSCode, by far the most used IDE, is also very popular among front-end developers. It’s free, it’s open source, and it has a lot of great features like smart tips, a plug-in store, Git integration, and more, but there’s another feature that many developers ignore — Run and Debug.

You might say, want anything Debug, I console.log a shuttle around the world. Yes, this is the debugging method that many people use today. But since VS Code has this feature, give it a try and you may learn something new

Introduction to the

One of the key features of VS Code is its powerful debugging function. The built-in debugger helps developers quickly edit, compile, and debug.

VS Code’s built-in debugger supports the Node.js runtime and can debug JavaScript, TypeScript, and any other language that can be compiled into JavaScript.

If you want to debug other languages and runtimes, including but not limited to PHP, Ruby, Go, C#, etc., you can find the relevant Debugger extension in the extension store and install it, which we won’t cover here.

Simple debugging

In order to facilitate our understanding of common functions, it is easier to learn related functions by debugging directly. Here we use a simple Node.js project as an example for debugging.

Start with app.js:

let msg = 'Hello world';
console.log(msg);
let numA = 6;
let numB = 13;
let num = numA + numB;
console.log(num);
Copy the code

So we have a simple Node.js program.

Next, click the Run and Debug icon in the left menu (icon is a bug + start, as the name implies debug&Run). Here is the initialization panel; Then we add breakpoints where we need them in our code:

Run and Debug directly:

The program runs and stops at the breakpoint. The debug panel is also activated, showing panels for variables, monitoring, call stacks, and breakpoints. Click the first icon in the debug action bar above (continue, F5) and the program will go to the next breakpoint and the variables panelmsgThe variable is updated:

Continue until the last breakpoint is broken, and our debugging step is complete. This is the simplest oneNode.jsThe debugging process of a program.

Of course, we will not have such a simple program in actual development, so let’s take a look at the related functions in debugging in detail.

Function is introduced

Although the example above is the Node.js project, most of the concepts and features are common to other debuggers as well.

Run panels and menus

We have already seen the run panel in the above example. Click the “Run and Debug” icon on the left to open the panel. The Run panel displays all the relevant information about the run and debug.

If launch.json has not been configured, VS Code will display the initial state panel. In this example, we did not configure it, so the display is the initial state:

In addition to the icon on the left, you can also Run using the top-level menu at the top. The command here is basically the same as in the panel:

You can also check it out here when you can’t remember the shortcut keys

A launch configuration

In the example above we selected “Run and debug” and VS Code directly started the debug step using the built-in Node.js debug configuration. In most scenarios, however, we don’t have this simple debugging. It’s important to create a custom launch profile where you can save debugging details.

VS Code stores debugging configuration information in a launch.json file in the.vs Code directory (the.vs Code directory is typically located in the project root directory).

To create a launch.json file, click “Create a launch.json” in the Run initialization panel:

VS Code will try to automatically detect the current debugging environment. If it fails, we need to manually select it ourselves:

chooseNode.jsAfter that, VS Code automatically generates the configuration file and.vs Code directory. Here is theNode.jsThe defaultlaunch.json:

{
    // Use IntelliSense to learn about related attributes.
    // Hover to view descriptions of existing properties.
    / / for more information, please visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0"."configurations": [{"type": "pwa-node"."request": "launch"."name": "Launch Program"."skipFiles": [
                "<node_internals>/**"]."program": "${workspaceFolder}/app.js"}}]Copy the code

It’s important to note that the properties in the Launch configuration can vary from one debugger to the next. You can use VS Code’s built-in smart hints feature to see what properties are available, and the Hover property can see help messages.

Don’t assume that properties that exist in one debugger will work in another debugger. Make sure all configurations make sense before debugging.

Launch and attach

In VS Code, there are two core debug modes, Launch and Attach, which provide developers with two different types of workflows.

The easiest way to understand these two workflows is:

  • The launch configuration can be interpreted as VS Code’s instructions for launching debuggers;
  • Attach configuration is how to connect VS Code’s debugger to a running application or process;

VS Code’s debugging supports starting a program in debug mode or attaching it to an already running program in debug mode. Which debugging configuration to use depends on our debugging requirements.

Launch properties

Json, you can use VS Code’s Intelligent prompt (Command +I) to view all available properties:

The following attributes are mandatory for each launch profile:

  • type– The type of debugger.
  • request– Request type, currently supports Launch and Attach
  • name– The name displayed in the Debug startup configuration drop-down menu

Here are some optional configuration properties:

  • presentation– inpresentationObject, withorder.group, andhiddenProperties can be sorted, grouped, and hidden from the debug configuration drop-down menu and quick-select debug options.
  • preLaunchTask– You can start a task before starting a debug session
  • postDebugTask– Start a task after debugging
  • internalConsoleOptions– This property controls the visibility of the debug console panel.
  • debugServer – For debug Extension authors onlyThis property allows you to connect to a specific port instead of starting the debug adapter.
  • serverReadyAction– Open a URL in a Web browser if you want to output a specific message to the debug console or integration terminal from a program under debugging.

Many debuggers support the following properties:

  • program– The executable program or file to run when the debugger is started
  • args– Parameters passed to the program for debugging
  • env– Environment variables (nullValues can be used to “undefine” a variable.)
  • envFile– Path to the. Env file with environment variables
  • cwd– The current working directory for finding dependencies and other files
  • port– Port to connect to a running process
  • stopOnEntry– Stop immediately when the program starts
  • console– Which console to use, for exampleinternalConsole.integratedTerminal, or externalTerminal

Variable substitution

VS Code provides many useful variables in launch.json and supports variable substitution within strings at startup. For example, ${workspaceFolder} gives the root path of the workspaceFolder, ${file} gives the file opened in the active editor, and ${env:Name} gives the value of the environment variable Name. You can view the variable references to see all the predefined variables.

debug

When a debug session is started, the debug toolbar appears at the top:

From left to right:

  • Continue/pauseF5: Executes to the next breakpoint
  • Single step overF10: Performs step debugging from the breakpoint
  • Step throughF11: goes inside the function
  • Step out ofshift+F11: Out of the function
  • restartshift+command+F11
  • The end of theshift+F5

Breakpoint (Breakpoints)

Click on the left margin of the editor to toggle breakpoints (the shortcut is F9). You can have more control over breakpoints in the Breakpoints section of the Run view.

The breakpoints on the left side of the editor are typically shown as red solid circles, and those that are not available are gray solid circles. This is also available in the breakpoints section if the debugger supports exiting on different errors or exceptions.

Record points (Logpoints)

A record point is a variant of a breakpoint that does not break into the debugger, but prints some information to the console. Record points are especially useful when debugging production services that cannot be paused or stopped.

The record point is displayed as a diamond shaped icon. Logging information is interpreted text but can also use computable expressions (wrapped in braces)

Just like regular breakpoints, record points can be enabled, disabled, and controlled by conditions.

Node. Js debug

There are three ways to debug Node.js in VS Code:

  • Used in VS Code’s integration terminalauto attachTo debug the program;
  • Debug the terminal using JavaScript
  • Use launch configuration, or attach to other applications

Auto Attach

When Auto Attach is enabled, the Node debugger is automatically attached to the Node.js process started in VS Code.

Command+Shift+P open Enter Auto Attach to open function:

Of the three choices here, we just choose Smart. After restarting VS Code, the debugger will be automatically attached when the application is started. The status of Auto Attach will be displayed in the status bar below. You can also click to change it.

JavaScript integration terminal

Similar to Auto Attach, the JavaScript debug terminal can automatically debug any Node.js application you run on the terminal. Select JavaScript Debug Terminal from the drop-down list box on the Terminal:

Launch:

Configuring launch.json for debugging is a traditional debugging method. It can be configured according to your own project code requirements and has high flexibility.

In addition to starting node.js directly with the Node command, we can also debug it using NPM or other tools through configuration.

  • Any program available on PATH (such as NPM, gulp, and so on) can be usedruntimeExecutableProperty, and arguments can be placed inruntimeArgsThe incoming.
  • If the NPM script or other tool implicitly specifies the program to start, you do not need to set itprogramProperties.

In my last article, I wrote about NPM Install, an incomplete source debugging, doing this in this way.

SourceMap debugging

VS Code’s JavaScript debugger supports source maps that help debug escaped languages (such as Typescript, compressed or obfuscated JavaScript, etc.). Use the Source Map to step through the source code or to set breakpoints.

If the source Map does not exist in the original code, or if the Source Map is broken and cannot map the original code to the generated JavaScript successfully, the breakpoint is shown as unvalidated (gray hollow circle), as shown below:

The source map function is controlled by the sourceMaps property, which defaults to true. Source Map can only be used if source Map files are generated in the project code. Therefore, if Typescript, Babel, webpack, etc., we need to configure source Map files and then configure them. For details, see the official documentation of VScode-source map.

If you want to debug your Vue project using VS Code, see # How to Make debugging vue and React Code easier. This configuration is available in vue2 projects, but vue3 has not yet been implemented successfully.

Senior breakpoint

Finally, THERE are some advanced breakpoints in VS Code that you may not use in your daily debugging, but you can learn about.

Conditional breakpoint

One powerful debugging feature in VS Code is the ability to set conditions based on expressions, hit counts, or a combination of the two.

  • Expression condition: The breakpoint is hit whenever the expression evaluates to true.
  • Hit count: Hit Count controls how many times a breakpoint must be clicked to interrupt execution.

You can add conditions or hit counts when creating breakpoints or modifying existing breakpoints. In both cases, an inline text box with a drop-down menu opens, where you can enter an expression:

i=3, will stop at the breakpoint:

Or set the hit count:

Stop at breakpoint when hit count equals 5:

If the debugger does not support conditional breakpoints, the add and edit menus are not displayed.

Inline breakpoint

An inline breakpoint is hit only if the execution reaches the column associated with the inline breakpoint. Useful when debugging small code that contains multiple statements in a single line, such as for loops:

Add inline breakpoints with Shift +F9. Inline breakpoints are displayed inline in the editor.

conclusion

VSCode debugging is very powerful. The above is just a part of it, and there is much more to explore in the official documentation.

While it’s more intuitive to debug in the browser for vue.js, which has its own DevTool framework, debugging other Node.js applications with VS Code is very efficient.