Merge branch 'vnext' of github.com:Microsoft/vscode-docs into vnext

This commit is contained in:
Ornella 2020-12-08 13:24:18 -08:00
Родитель 9f9be05796 a7e94cb3ff
Коммит 53ea19cbcf
6 изменённых файлов: 197 добавлений и 165 удалений

Просмотреть файл

@ -186,7 +186,7 @@ Variables can be inspected in the **VARIABLES** section of the Run view or by ho
![Debug Variables](images/debugging/variables.png)
Variable values can be modified with the **Set Value** action from the variable's context menu.
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 view's **WATCH** section.

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c398cc7ea83e8f3e87a8251373bf0fa5f0af8574930b127268e8a3ba44962629
size 98777

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:dde36d4ecad42aff36be00813e155b77826b31b294d4d026c07c1488abbe6e2e
size 16056

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a2f7bf1c4b80a1912cf12587fb4541d8725fa8d31aee5f7869ca4a239ecd7aef
size 130051

Просмотреть файл

@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c761eaa6616f13d2dde99f0646f7fb19fab497b72c350e7e46f36fd9e125ab2c
size 112266

Просмотреть файл

@ -10,26 +10,106 @@ MetaSocialImage: /assets/docs/editor/debugging/Debugging.png
---
# Node.js debugging in VS Code
The Visual Studio Code editor has built-in debugging support for the [Node.js](https://nodejs.org/) runtime and can debug JavaScript, TypeScript, and many other languages that are transpiled into JavaScript. Setting up a project for Node.js debugging is usually straightforward with VS Code providing appropriate launch configuration defaults and snippets.
The Visual Studio Code editor has built-in debugging support for the [Node.js](https://nodejs.org/) 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.
>**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](/docs/editor/debugging.md) topic.
There are a few ways you can debug your Node.js programs in VS Code:
This Node.js debugging document goes into more detail about configurations and features for more advanced debugging scenarios. You'll find instruction for debugging with [source maps](/docs/nodejs/nodejs-debugging.md#source-maps), [stepping over external code](/docs/nodejs/nodejs-debugging.md#skipping-uninteresting-code-node-chrome), doing [remote debugging](/docs/nodejs/nodejs-debugging.md#remote-debugging), and much more.
- Use [auto attach](#_auto-attach) to debug process you run in VS Code's integrated terminal,
- Use the [JavaScript debug terminal](#_auto-attach-feature), in a similar way, or
- Use a [launch config](#_launch-configuration) to start your program, or [attach to a process](#_attaching-to-nodejs) launched outside of 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 (`kbstyle(F1)`) 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:
* `smart` (default) - If you execute a script outside of your `node_modules` folder or use a common 'runner' script like mocha or ts-node, the process will be debugged. You can configure the 'runner' script allow list using the **Auto Attach Smart Pattern** setting (`debug.javascript.autoAttachSmartPattern`).
* `always` - All Node.js processes launched in the Integrated Terminal will be debugged.
* `onlyWithFlag` - Only processes launched with the `--inspect` or `--inspect-brk` flag will be debugged.
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:
![Auto Attach](images/nodejs-debugging/auto-attach.gif)
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](#_launch-configuration-attributes) 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:
```js
"debug.javascript.terminalOptions": {
"skipFiles": [
"<node_internals>/**"
]
},
```
**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](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options). The glob patterns are configurable in the **debug.javascript.autoAttachSmartPattern** setting, which defaults to:
```js
[
"!**/node_modules/**", // exclude scripts in node_modules folders
"**/$KNOWN_TOOLS$/**" // but include some common tools
]
```
`$KNOWN_TOOLS$` is replaced list a list of common 'code runners' such as `ts-node`, `mocha`, `ava`, and so on. You can modify this list if these settings don't work. For example, to exclude `mocha` and include `my-cool-test-runner`, you could add two lines:
```js
[
"!**/node_modules/**",
"**/$KNOWN_TOOLS$/**",
"!**/node_modules/mocha/**", // use "!" to exclude all scripts in "mocha" node modules
"**/node_modules/my-cool-test-runner/**" // include scripts in the custom test runner
]
```
## JavaScript Debug Terminal
In a similar way to [auto attach](#_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 use the **Debug: Create JavaScript Debug Terminal** command from the command palette (`kbstyle(F1)`), or by selecting the **Create JavaScript Debug Terminal** from the terminal switcher dropdown.
![Create Debug Terminal](images/nodejs-debugging/create-debug-terminal.png)
### Additional Configuration
**Other Launch Configuration Properties**
You can apply [other properties normally found in launch.json](#_launch-configuration-attributes) 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:
```js
"debug.javascript.terminalOptions": {
"skipFiles": [
"<node_internals>/**"
]
},
```
## 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](/docs/nodejs/nodejs-debugging.md#source-maps), [stepping over external code](/docs/nodejs/nodejs-debugging.md#skipping-uninteresting-code-node-chrome), doing [remote debugging](/docs/nodejs/nodejs-debugging.md#remote-debugging), and much more.
If you'd like to watch an introductory video, see [Getting started with Node.js debugging](https://www.youtube.com/watch?v=2oFKNL7vYV8).
>**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](/docs/editor/debugging.md) topic.
## Launch configuration attributes
Debugging configurations are stored in a `launch.json` file located in your workspace's `.vscode` folder. An introduction into the creation and use of debugging configuration files is in the general [Debugging](/docs/editor/debugging.md#launch-configurations) topic.
Debugging configurations are stored in a `launch.json` file located in your workspace's `.vscode` folder. An introduction into the creation and use of debugging configuration files is in the general [Debugging](/docs/editor/debugging.md#launch-configurations) article.
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](https://github.com/microsoft/vscode-js-debug/blob/master/OPTIONS.md) documentation.
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](https://github.com/microsoft/vscode-js-debug/blob/master/OPTIONS.md) documentation.
The following attributes are supported in launch configurations of type `launch` and `attach`:
* `sourceMaps` - enable source maps by setting this to `true`. See section [Source maps](/docs/nodejs/nodejs-debugging.md#source-maps).
* `outFiles` - array of glob patterns for locating generated JavaScript files. See section [Source maps](/docs/nodejs/nodejs-debugging.md#source-maps).
* `restart` - restart session on termination. See section [Restarting debug session automatically](/docs/nodejs/nodejs-debugging.md#restarting-debug-sessions-automatically-when-source-is-edited).
* `resolveSourceMapLocations` - an array of glob patterns for locations where source maps should be parsed. See section [Source maps](/docs/nodejs/nodejs-debugging.md#source-maps).
* `timeout` - when restarting a session, give up after this number of milliseconds. See section [Attaching to Node.js](/docs/nodejs/nodejs-debugging.md#attaching-to-nodejs).
* `stopOnEntry` - break immediately when the program launches.
* `localRoot` - VS Code's root directory. See section [Remote debugging](/docs/nodejs/nodejs-debugging.md#remote-debugging) below.
@ -48,16 +128,17 @@ These attributes are only available for launch configurations of request type `l
* `runtimeVersion` - if "[nvm](https://github.com/creationix/nvm)" (or "[nvm-windows](https://github.com/coreybutler/nvm-windows)") or "[nvs](https://github.com/jasongin/nvs)" is used for managing Node.js versions, this attribute can be used to select a specific version of Node.js. See section [Multi version support](/docs/nodejs/nodejs-debugging.md#multi-version-support) below.
* `env` - optional environment variables. This attribute expects environment variables as a list of string typed key/value pairs.
* `envFile` - optional path to a file containing environment variable definitions. See section [Load environment variables from external file](/docs/nodejs/nodejs-debugging.md#load-environment-variables-from-external-file-node) below.
* `console` - kind of console to launch the program (`internalConsole`, `integratedTerminal`, `externalTerminal`). See section [Node Console](/docs/nodejs/nodejs-debugging.md#node-console) below.
* `console` - the console to launch the program (`internalConsole`, `integratedTerminal`, `externalTerminal`). See section [Node Console](/docs/nodejs/nodejs-debugging.md#node-console) below.
* `outputCapture` - if set to `std`, output from the process stdout/stderr will be shown in the Debug Console, instead of listening to output over the debug port. This is useful for programs or log libraries that write directly to the stdout/stderr streams instead of using `console.*` APIs.
* `autoAttachChildProcesses` - track all subprocesses of debuggee and automatically attach to those that are launched in debug mode. See section [Automatically attach debugger to Node.js subprocesses](/docs/nodejs/nodejs-debugging.md#automatically-attach-debugger-to-nodejs-subprocesses) below.
This attribute is only available for launch configurations of request type `attach`:
* `restart` - restart the connection on termination. See section [Restarting debug session automatically](/docs/nodejs/nodejs-debugging.md#restarting-debug-sessions-automatically-when-source-is-edited).
* `protocol` - debug protocol to use. See section [Supported Node-like runtimes](/docs/nodejs/nodejs-debugging.md#supported-nodelike-runtimes) above.
* `port` - debug port to use. See sections [Attaching to Node.js](/docs/nodejs/nodejs-debugging.md#attaching-to-nodejs) and [Remote debugging](/docs/nodejs/nodejs-debugging.md#remote-debugging).
* `address` - TCP/IP address of the debug port. See sections [Attaching to Node.js](/docs/nodejs/nodejs-debugging.md#attaching-to-nodejs) and [Remote debugging](/docs/nodejs/nodejs-debugging.md#remote-debugging).
* `processId` - the debugger tries to attach to this process after having sent a USR1 signal. With this setting, the debugger can attach to an already running process that was not started in debug mode. When using the `processId` attribute the debug port is determined automatically based on the Node.js version (and the used protocol) and cannot be configured explicitly. So don't specify a `port` attribute.
* `processId` - the debugger tries to attach to this process after having sent a USR1 signal. With this setting, the debugger can attach to an already running process that was not started in debug mode. When using the `processId` attribute, the debug port is determined automatically based on the Node.js version (and the used protocol) and cannot be configured explicitly. So don't specify a `port` attribute.
* `continueOnAttach` - whether to continue the process if it's paused when we attach to it. This option is useful if you launch your program with `--inspect-brk`.
### Launch configurations for common scenarios
@ -69,14 +150,14 @@ You can also bring up the snippets with the **Add Configuration...** button in t
![Add Configuration button](images/nodejs-debugging/add-configuration-button.png)
Here is the list of all snippets:
These are the available snippets:
- **Launch Program**: Launch a Node.js program in debug mode.
- **Launch via npm**: Launch a Node.js program through an npm 'debug' script. If you have defined an npm debug script in your package.json, you can use this directly from your launch configuration. Make sure that the debug port used in the npm script, corresponds to the port specified in the snippet.
- **Attach**: Attach to the debug port of a locally running Node.js program. Make sure that the Node.js program to debug has been started in debug mode and the debug port used is the same as the one specified in the snippet.
- **Attach to Remote Program**: Attach to the debug port of a Node.js program running on the host specified by the `address` attribute. Make sure that the Node.js program to debug has been started in debug mode and the debug port used is the same as the one specified in the snippet. To help VS Code mapping source files between your workspace and the filesystem of the remote host, make sure to specify correct paths for the `localRoot`and `remoteRoot` attributes.
- **Launch via npm**: Launch a Node.js program through an npm 'debug' script. If you have defined an npm debug script in your package.json, you can use it directly from your launch configuration. Make sure that the debug port used in the npm script, corresponds to the port specified in the snippet.
- **Attach**: Attach to the debug port of a locally running Node.js program. Make sure that the Node.js program to debug has been started in debug mode, and the debug port used is the same as the one specified in the snippet.
- **Attach to Remote Program**: Attach to the debug port of a Node.js program running on the host specified by the `address` attribute. Make sure that the Node.js program to debug has been started in debug mode, and the debug port used is the same as the one specified in the snippet. To help VS Code map source files between your workspace and the filesystem of the remote host, make sure to specify correct paths for the `localRoot`and `remoteRoot` attributes.
- **Attach by Process ID**: Open the process picker to select a node or gulp process for debugging. With this launch configuration, you can even attach to a node or gulp process that was not started in debug mode.
- **Nodemon Setup**: Use nodemon to relaunch a debug session automatically whenever the JavaScript source has changed. Make sure that you have nodemon installed globally. Please note that terminating the debug session only terminates the program to debug, not nodemon itself. To terminate nodemon, press `kbstyle(Ctrl+C)` in the Integrated Terminal.
- **Nodemon Setup**: Use nodemon to relaunch a debug session automatically whenever the JavaScript source has changed. Make sure that you have nodemon installed globally. Note that terminating the debug session only terminates the program to debug, not nodemon itself. To terminate nodemon, press `kbstyle(Ctrl+C)` in the Integrated Terminal.
- **Mocha Tests**: Debug mocha tests in a `test` folder of your project. Make sure that your project has 'mocha' installed in its `node_modules` folder.
- **Yeoman generator**: Debug a yeoman generator. The snippet asks you to specify the name of the generator. Make sure that your project has 'yo' installed in its `node_modules` folder and that your generated project has been installed for debugging by running `npm link` in the project folder.
- **Gulp task**: Debug a gulp task. Make sure that your project has 'gulp' installed in its `node_modules` folder.
@ -99,7 +180,7 @@ Let's look at an 'npm' example. If your `package.json` has a 'debug' script, for
```json
"scripts": {
"debug": "node --nolazy myProgram.js"
"debug": "node myProgram.js"
},
```
@ -120,19 +201,19 @@ the corresponding launch configuration would look like this:
### Multi version support
If you are using '[nvm](https://github.com/creationix/nvm)' (or '[nvm-windows](https://github.com/coreybutler/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 '[nvm](https://github.com/creationix/nvm)' (or '[nvm-windows](https://github.com/coreybutler/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:
```json
{
"type": "node",
"request": "launch",
"name": "Launch test",
"runtimeVersion": "7.10.1",
"runtimeVersion": "14",
"program": "${workspaceFolder}/test.js"
}
```
If you are using '[nvs](https://github.com/jasongin/nvs)' to manage your Node.js versions, it is possible to use `runtimeVersion` attribute to select a specific version of Node.js:
If you are using '[nvs](https://github.com/jasongin/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:
```json
{
@ -144,11 +225,11 @@ If you are using '[nvs](https://github.com/jasongin/nvs)' to manage your Node.js
}
```
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 itself. So you will 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.
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.
If you omit the minor and patch version and have, for example, `"runtimeVersion": "14"`, then the most recent `14.x.y` version installed on your system will be used.
### Load environment variables from external file (node)
### 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:
@ -161,7 +242,7 @@ The VS Code Node debugger supports loading environment variables from a file and
Any environment variable specified in the `env` dictionary will override variables loaded from the file.
Here is an example of an `.env` file:
Here's an example of an `.env` file:
```
USER=doe
@ -178,71 +259,34 @@ lines="foo\nbar"
## Attaching to Node.js
If you want to attach the VS Code debugger to a Node.js program, launch Node.js in VS Code's integrated terminal as follows:
If you want to attach the VS Code debugger to an external Node.js program, launch Node.js as follows:
```
node --inspect program.js
```
or if the program should not start running but must wait for the debugger to attach:
or if the program shouldn't start running, but must wait for the debugger to attach:
```
node --inspect-brk program.js
```
Now you have three options for attaching the debugger to your program:
Now you have a couple options for attaching the debugger to your program:
- have VS Code automatically attach to the program, or
- open a "process picker" that lists all potential candidate processes and let you pick one, or
- create an "attach" configuration that explicitly specifies all configuration options and then press **F5**.
Let's go through these options in detail:
### Auto Attach feature
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. There are three modes for auto attach, configurable in the **debug.javascript.autoAttachFilter** setting:
* `smart` - If you execute a script outside of your `node_modules` folder or use a common 'runner' script like mocha or ts-node, the process will be debugged. You can configure the 'runner' script allowlist using the **Auto Attach Smart Pattern** setting (`debug.javascript.autoAttachSmartPattern`). This is the default.
* `always` - All Node.js processes launched in the Integrated Terminal will be debugged.
* `onlyWithFlag` - Only processes launched with the `--inspect` or `--inspect-brk` flag will be debugged.
To enable the feature, either use the **Toggle Auto Attach** action or, if the Node debugger is already activated, use the **Auto Attach** Status bar item.
After enabling **Auto Attach**, the debugger should attach to your program within a second:
![Auto Attach](images/nodejs-debugging/auto-attach.gif)
**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](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options). This list is configurable in the **debug.javascript.autoAttachSmartPattern** setting, which defaults to:
```js
[
"!**/node_modules/**", // exclude scripts in node_modules folders
"**/$KNOWN_TOOLS$/**" // but include some common tools
]
```
`$KNOWN_TOOLS$` is replaced list a list of common 'code runners' such as `ts-node`, `mocha`, `ava`, and so on. You can modify this list if these settings don't work. For example, to exclude `mocha` and include `my-cool-test-runner`, you could add two lines:
```js
[
"!**/node_modules/**",
"**/$KNOWN_TOOLS$/**",
"!**/node_modules/mocha/**", // use "!" to exclude all scripts in "mocha" node modules
"**/node_modules/my-cool-test-runner/**" // include scripts in the custom test runner
]
```
### Attach to Node Process action
The **Attach to Node Process** action opens a Quick Pick menu that lists all potential processes that are available to the Node.js debugger:
The **Attach to Node Process** command from the command palette (`kbstyle(F1)`) opens a Quick Pick menu that lists all potential processes that are available to the Node.js debugger:
![Node.js Process picker](images/nodejs-debugging/process-picker.png)
The individual processes listed in the picker show the debug port and the detected protocol in addition to the process ID. You should find your Node.js process in that list and after selecting it, the Node.js debugger tries to attach to it.
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.
In addition to Node.js processes, the picker also shows other programs that were launched with one of the various forms of `--debug` or `--inspect` arguments. This makes it possible to attach to Electron's or VS Code's helper processes.
In addition to Node.js processes, the picker also shows other programs that were launched with one of the various forms `--inspect` arguments. This makes it possible to attach to Electron's or VS Code's helper processes.
### Setting up an "Attach" configuration
@ -259,7 +303,7 @@ The simplest "attach" configuration looks like this:
}
```
The port `9229` is the default debug port of the `--inspect` and `--inspect-brk` options. To use a different port (for example `12345`), add it to the options like this: `--inspect=12345` and `--inspect-brk=12345` and change the `port` attribute in the launch configuration accordingly.
The port `9229` is the default debug port of the `--inspect` and `--inspect-brk` options. To use a different port (for example `12345`), add it to the options like this: `--inspect=12345` and `--inspect-brk=12345` and change the `port` attribute in the launch configuration to match.
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:
@ -272,9 +316,9 @@ If you want to attach to a Node.js process that hasn't been started in debug mod
}
```
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 binds to the process picker (from above) and that lets you conveniently pick the process from a list of Node.js processes.
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).
By using the `PickProcess` variable the launch configuration looks like this:
Using the `PickProcess` variable the launch configuration looks like this:
```json
{
@ -303,26 +347,39 @@ Note that on the Windows operating system, pressing **Stop** always forcibly kil
## Source maps
The Node.js debugger of VS Code supports JavaScript source maps that help debugging of transpiled languages, for example, TypeScript or minified/uglified JavaScript. With source maps, it is 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).
The Node.js debugger of VS Code supports JavaScript 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).
Source maps can be generated with two kinds of inlining:
The source map feature is controlled by the `sourceMaps` attribute that defaults to `true`. This means that node debugging always tries to use source maps (if it can find any) and as a consequence, you can even specify a source file (for example, app.ts) with the `program` attribute. If you need to disable source maps for some reason, you can set the `sourceMaps` attribute to `false`.
* **Inlined source maps**: the generated JavaScript file contains the source map as a data URI at the end (instead of referencing the source map through a file URI).
* **Inlined source**: the source map contains the original source (instead of referencing the source through a path).
### Tool Configuration
VS Code supports both the inlined source maps and the inlined source.
Since source maps are not always automatically created, you should make sure to configure your transpiler to create them. For example:
The source map feature is controlled by the `sourceMaps` attribute that defaults to `true`. This means that node debugging always tries to use source maps (if it can find any) and as a consequence, you can even specify a source file (for example, app.ts) with the `program` attribute.
**TypeScript**
If you need to disable source maps for some reason, you can set the `sourceMaps` attribute to `false`.
Since source maps are not always automatically created, you must configure the transpiler you are using to create them. For TypeScript, this can be done in the following way:
For TypeScript, you can enable sourcemaps by passing `--sourceMap` to `tsc`, or by adding `"sourceMap": true` in your tsconfig.json file.
```
tsc --sourceMap --outDir bin app.ts
```
By default, VS Code will search your entire workspace for sourcemaps, but in very large workspaces, this search might be slow. You can configure the locations where VS Code will search for source maps by setting the `outFiles` attribute in your `launch.json`. For example, this will discover sourcemaps for all `.js` files in the `bin` folder:
**Babel**
For Babel, you'll want to set the [sourceMaps](https://babeljs.io/docs/en/options#sourcemaps) option to `true`, or pass the `--source-maps` option when compiling your code.
```
npx babel script.js --out-file script-compiled.js --source-maps
```
**Webpack**
Webpack has [numerous](https://webpack.js.org/configuration/devtool/) 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
By default, VS Code will search your entire workspace, excluding `node_modules`, for sourcemaps. In large workspaces, this search might be slow. You can configure the locations where VS Code will search for source maps by setting the `outFiles` attribute in your `launch.json`. For example, this configuration will only discover sourcemaps for `.js` files in the `bin` folder:
```json
{
@ -339,13 +396,28 @@ By default, VS Code will search your entire workspace for sourcemaps, but in ver
}
```
Note that the `outFiles` should match your JavaScript files, not the source map files (which may end in `.map` instead of `.js`).
### Source Map Resolution
By default, only source maps in your `outFiles` will be resolved. This behavior is used to prevent dependencies from interfering with breakpoints you set. For example, if you had a file `src/index.ts` and a dependency had a source map that referenced `webpack:///./src/index.ts`, that would incorrectly resolve to your source file and could lead to surprising results.
You can configure this behavior by setting the `resolveSourceMapLocations` option. If set to `null`, every source map will be resolved. For example, this configuration will additionally allow source maps in `node_modules/some-dependency` to be resolved:
```js
"resolveSourceMapLocations": [
"out/**/*.js",
"node_modules/some-dependency/**/*.js",
]
```
### 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 really 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.
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.
This 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.
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.
Please note that 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.
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
@ -359,29 +431,28 @@ Finally, the debug adapter searches for the full path of `app.ts` in this result
Here are some things to try when your breakpoints turn gray:
* Do you have `"sourceMaps": false` in your `launch.json`?
* Did you build with source maps enabled? Are there `.js.map` files, or inlined source maps in your `.js` files?
* While debugging, run the **Debug: Create Diagnostic Information for Current Session** command. This command will bring up a tool that can provide hints to help you resolve any issues from the command palette (`kbstyle(F1)`).
* Did you build with source maps enabled? Make sure there are `.js.map` files, or inlined source maps in your `.js` files.
* Are the `sourceRoot` and `sources` properties in your source map correct? Can they be combined to get the correct path to the `.ts` file?
* Are you using Webpack? By default, it outputs paths with a `webpack:///` prefix, which the debug adapter can't resolve. You can change this in your Webpack configuration with the `devtoolModuleFilenameTemplate` option, or try using the 'inspector' protocol, which provides some extra options for resolving these paths.
* Have you opened the folder in VS Code with the incorrect case? It's possible to open folder `foo/` from the command line like `code FOO` in which case source maps may not be resolved correctly.
* Try searching for help with your particular setup on Stack Overflow or by filing an issue on GitHub.
* Try adding a `debugger` statement. If it breaks into the `.ts` file there, but breakpoints at that spot don't bind, that is useful information to include with a GitHub issue.
## Remote debugging
The Node.js debugger supports remote debugging for versions of Node.js >= 4.x. Specify a remote host via the `address` attribute. Here is an example:
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:
```json
{
"type": "node",
"request": "attach",
"name": "Attach to remote",
"address": "TCP/IP address of process to be debugged",
"address": "192.168.148.2", // <- remote address here
"port": 9229
}
```
By default, VS Code will stream the debugged source from the remote Node.js folder to the local VS Code and show it in a read-only editor. You can step through this code, but cannot modify it. If you want VS Code to open the editable source from your workspace instead, you can setup a mapping between the remote and local locations. A `localRoot` and a `remoteRoot` attribute can be used to map paths between a local VS Code project and a (remote) Node.js folder. This works even locally on the same system or across different operating systems. Whenever a code path needs to be converted from the remote Node.js folder to a local VS Code path, the `remoteRoot` path is stripped off the path and replaced by `localRoot`. For the reverse conversion, the `localRoot` path is replaced by the `remoteRoot`.
By default, VS Code will stream the debugged source from the remote Node.js folder to the local VS Code and show it in a read-only editor. You can step through this code, but cannot modify it. If you want VS Code to open the editable source from your workspace instead, you can set up a mapping between the remote and local locations. A `localRoot` and a `remoteRoot` attribute can be used to map paths between a local VS Code project and a (remote) Node.js folder. This works even locally on the same system or across different operating systems. Whenever a code path needs to be converted from the remote Node.js folder to a local VS Code path, the `remoteRoot` path is stripped off the path and replaced by `localRoot`. For the reverse conversion, the `localRoot` path is replaced by the `remoteRoot`.
```json
{
@ -401,25 +472,6 @@ Two frequently used applications of remote debugging are:
If you are running Node.js inside a [Docker](https://www.docker.com) container, you can use the approach from above to debug Node.js inside the Docker container and map back the remote source to files in your workspace. We have created a "recipe" on [GitHub](https://github.com/microsoft/vscode-recipes) that walks you through on how to set this up [Node.js in Docker with TypeScript](https://github.com/microsoft/vscode-recipes/tree/master/Docker-TypeScript).
* **debugging Node.js in the Windows Subsystem for Linux (WSL):**
If you want to run Node.js in the [Windows Subsystem for Linux](https://docs.microsoft.com/windows/wsl/install-win10) (WSL), you can use the approach from above as well. However, to make this even simpler, we've introduced a `useWSL` flag to automatically configure everything so that Node.js runs in the Linux subsystem and source is mapped to files in your workspace.
Here is the simplest debug configuration for debugging `hello.js` in WSL:
```json
{
"type": "node",
"request": "launch",
"name": "Launch in WSL",
"useWSL": true,
"program": "${workspaceFolder}/hello.js"
}
```
**Please note**: With the arrival of the [Remote - WSL](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl) extension, VS Code got universal support for [Windows Subsystem for Linux](https://docs.microsoft.com/windows/wsl) (WSL). Consequently,
the `useWSL` debug configuration attribute has been deprecated and support for it will be dropped soon. For more details, please see our [Developing in WSL](https://code.visualstudio.com/docs/remote/wsl) documentation.
## 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 view:
@ -461,7 +513,6 @@ Alternatively you can start your program `server.js` via **nodemon** directly wi
"request": "launch",
"runtimeExecutable": "nodemon",
"program": "${workspaceFolder}/server.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
@ -471,34 +522,39 @@ Alternatively you can start your program `server.js` via **nodemon** directly wi
>**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 (node)
## 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 very time-consuming. The **Restart Frame** action allows you to reenter the current function after you have changed variables with the **Set Value** action:
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:
<p>
<img alt="restart frame" src="https://az754404.vo.msecnd.net/public/restartFrame.gif" />
</p>
Note that **Restart Frame** won't unroll any state changes, so it may not always work as expected.
Make sure to use a Node.js version >= 5.11 since earlier versions do not work in all situations.
**Restart Frame** won't roll back mutation to state outside of the function, so it may not always work as expected.
## Breakpoints
### Function breakpoints
### Conditional Breakpoints
The Node.js debugger only supports function breakpoints when the "legacy" protocol is used (that is when targeting Node.js < 8.0 versions). In addition, be aware of the following limitations when using function 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":
- Function breakpoints only work for global, non-native functions.
- Function breakpoints can only be created if the function has been defined (and has been seen by the debugger).
![Conditional breakpoint](images/nodejs-debugging/conditional-breakpoint.gif)
<p>
<img alt="function breakpoint" src="https://az754404.vo.msecnd.net/public/function-breakpoint.gif" />
</p>
### Logpoints
### Breakpoint hit counts
Something 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: {myVariable.property}`.
The 'hit count condition' controls how many times a breakpoint needs to be hit before it will 'break' execution. The hit count syntax supported by the Node.js debugger is either an integer or one of the operators `<`, `<=`, `==`, `>`, `>=`, `%` followed by an integer.
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`:
![Logpoint](images/nodejs-debugging/logpoint-breakpoint.gif)
### 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".
![Hit count breakpoint](images/nodejs-debugging/hit-count-breakpoint.gif)
The hit count syntax supported by the Node.js debugger is either an integer or one of the operators `<`, `<=`, `==`, `>`, `>=`, `%` followed by an integer.
Some examples:
@ -523,9 +579,9 @@ This breakpoint validation occurs when a session starts and the breakpoints are
![Breakpoint Actions](images/nodejs-debugging/breakpointstoolbar.png)
## Skipping uninteresting code (node, chrome)
## Skipping uninteresting code
VS Code Node.js debugging has a feature to avoid source code that you don't want to step through (AKA '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.
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.
For example, using:
@ -549,8 +605,9 @@ Built-in **core modules** of Node.js can be referred to by the 'magic name' `<no
The exact 'skipping' rules are as follows:
* If you step into a skipped file, you won't stop there - you will stop on the next executed line that is not in a skipped file.
* If you have set the option to break on thrown exceptions, then you won't break on exceptions thrown from skipped files.
* If you have set the option to break on thrown exceptions, then you won't break on exceptions thrown from skipped files unless they bubble up into a non-skipped file.
* If you set a breakpoint in a skipped file, you will stop at that breakpoint, and you will be able to step through it until you step out of it, at which point normal skipping behavior will resume.
* The location of console messages from inside skip files will be shown as the first non-skipped location in the call stack.
Skipped source is shown in a 'dimmed' style in the CALL STACK view:
@ -575,44 +632,7 @@ In the following (`legacy` protocol-only) example all but a 'math' module is ski
## 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.
If you need to debug older Node.js programs, you can revert to the legacy debugger by setting `debug.javascript.usePreview: false`. However, you should also consider upgrading, as Node versions prior to 10 are end-of-life and no longer receive security updates as of April 2020.
### Legacy Debugger Protocols
Since the VS Code Node.js debugger communicates to the Node.js runtimes through [wire protocols](https://en.wikipedia.org/wiki/Wire_protocol), the set of supported runtimes is determined by all runtimes supporting the wire protocols.
Today two wire protocols exist:
- **legacy**: the original [V8 Debugger Protocol](https://github.com/buggerjs/bugger-v8-client/blob/master/PROTOCOL.md), which is currently supported by older runtimes.
- **inspector**: the new [V8 Inspector Protocol](https://chromedevtools.github.io/debugger-protocol-viewer/v8/) is exposed via the `--inspect` flag in Node.js versions >= 6.3. It addresses most of the limitations and scalability issues of the legacy protocol.
Currently these protocols are supported by specific version ranges of the following runtimes:
Runtime | 'Legacy' Protocol | 'Inspector' Protocol
----------|-------------------|----------
io.js | all | no
Node.js | < 8.x | >= 6.3 (Windows: >= 6.9)
Electron | < 1.7.4 | >= 1.7.4
Chakra | all | not yet
Although it appears to be possible that the VS Code Node.js debugger picks the best protocol always automatically,
we've decided for a 'pessimistic approach' with an explicit launch configuration attribute `protocol` and the following values:
- **`auto`**: tries to automatically detect the protocol used by the targeted runtime. For configurations of request type `launch` and if no `runtimeExecutable` is specified, we try to determine the version by running node from the PATH with an `--version` argument. If the node version is >= 8.0, the new 'inspector' protocol is used. For configurations of request type 'attach', we try to connect with the new protocol and if this works, we use the 'inspector' protocol. We only switch to the new 'inspector' protocol for versions >= 6.9 because of severe problems in earlier versions.
- **`inspector`**: forces the node debugger to use the 'inspector' protocol-based implementation. This is supported by node versions >= 6.3 and Electron versions >= 1.7.4.
- **`legacy`**: forces the node debugger to use the 'legacy' protocol-based implementation. This is supported by node versions < v8.0 and Electron versions < 1.7.4.
Starting with VS Code 1.11, the default value for the `protocol` attribute is `auto`.
If your runtime supports both protocols, here are a few additional reasons for using the `inspector` protocol over `legacy`:
* It can be more stable when debugging very large JavaScript objects. The legacy protocol can become painfully slow when sending large values between the client and server.
* If you are using an ES6 Proxy in your app, you can prevent a Node v7+ runtime from crashing when being debugged via the `inspector` protocol. This issue is tracked in [Microsoft/vscode#12749](https://github.com/microsoft/vscode/issues/12749).
* Debugging via the `inspector` protocol can handle some trickier source map setups. If you have trouble setting breakpoints in source mapped files, try using `inspector`.
We try to keep feature parity between both protocol implementations but this becomes more and more difficult because the technology underlying `legacy` is deprecated whereas the new `inspector` evolves quickly. For this reason, we specify the supported protocols if a feature is not supported by both `legacy` and `inspector`.
The current VS Code JavaScript debugger supports Node version at or above 8.x, recent Chrome versions, and recent Edge versions (via the `pwa-msedge` launch type).
## Next steps
@ -654,4 +674,4 @@ If your main script is inside a symlinked path, then you will also need to add t
If you use esm or pass `--experimental-modules` to Node.js in order to use ECMAScript modules, you can pass these options through the `runtimeArgs` attribute of `launch.json`:
* `"runtimeArgs": ["--experimental-modules"]` - Use the [experimental ECMAScript modules support](https://nodejs.org/api/esm.html) in Node v8.5.0+
* `"runtimeArgs": ["-r", "esm"]` - Use the [esm ES module loader](https://github.com/standard-things/esm) (Note that `["-r esm"]` without a comma won't work)
* `"runtimeArgs": ["-r", "esm"]` - Use the [esm ES module loader](https://github.com/standard-things/esm) (`["-r esm"]` without a comma won't work)