Как посмотреть ошибки в visual studio code

The corresponding cmd name in VS Keybindings is editor.action.showHover. On mac for me the key combo was: cmd+k cmd+i. I’m not sure what it is on windows but you can find out through your command palette by typing show hover. It will show you the current keybinding and you can execute it as well.

If you would like you can remap it like this:

{
    "key": "ctrl+e",
    "command": "editor.action.showHover",
    "when": "editorTextFocus"
}

With that, if your cursor is within an error/warning squiggly line, you can hit ctrl+e to show what you would normally see with hover.

To make the box disappear, hit escape.

UPDATE 2019

ES-Lint has introduced a new task in VS Code. You have to enable it in the workspace setings.

"eslint.lintTask.enable": true

Just go to terminal menu and select run task, then choose

eslint: lint whole folder

You can also auto-fix most problems by running the following command in the terminal:

.node_modules.bineslint.cmd --fix .

Reference: https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

While we still await the problem scanner in VS Code, this is a good enough alternative if you use eslint.

OLD ANSWER

Here is how you can see all problems in less than 10 seconds.

You use a little trick.

Open replace all in files Ctrl + Shift + H.

Replace ; with ;

Hit replace all. That’s it. Now, check Problems.

The assumption here is that all files have at least one semicolon. For
bigger projects, if you get a warning asking you to refine your
search, just enter something that is common in all files but is not
present a lot.

Very important: Make sure to check the Super cool! But i don’t use eslint section! Wich provide a global solution! By setting up tasks! And explained in details!

Note: If you feel the document is blottered! Make sure to skim and get to the titles that catch you! Even though every section may matter! (TLDS (TOO LONG DO SKIM)).

Javascript and Eslint

To add upon @Ajay Raghav answer!

This section show how to run the task on question! And the output of the execution!

For javascript, Vscode Eslint extension provide such a feature! Which if you are using Eslint (and not jshint) then you are having it already installed!

Usage as described on @Ajay Raghav answer! Are explained on the Eslint extension page!

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

eslint.lintTask.enable: whether the extension contributes a lint task to lint a whole workspace folder.

eslint.lintTask.options: Command line options applied when running the task for linting the whole workspace (https://eslint.org/docs/user-guide/command-line-interface). An example to point to a custom .eslintrc.json file and a custom .eslintignore is:

{
  "eslint.lintTask.options": "-c C:/mydirectory/.eslintrc.json --ignore-path C:/mydirectory/.eslintignore ."
}

Using the extension with VS Code’s task running

From the doc:

The extension is linting an individual file only on typing. If you want to lint the whole workspace set eslint.lintTask.enable to true and the extension will also contribute the eslint: lint whole folder task. There is no need anymore to define a custom task in tasks.json.

If you are not familiar with task! Here how you use the above!

  • Go to Command pallet (CTRL + P + SHIFT)
  • > tasks run
  • Hit Tasks: run Task
  • You’ll find eslint: lint whole folder
  • Hit and that’s it

enter image description here

enter image description here

If eslint have no configuration setup! You’ll get the following error!

enter image description here

If as such, Run eslint --init

And follow the interactive terminal!

Note if you don’t have eslint command avaialble globally!

Intall it globally by running npm i -g eslint!

Result of the run

First the task run on the terminal!

enter image description here

enter image description here

You can see a detailed report! You can use the click link on terminal feature (CTRL + CLICK)! To directly open the file in question!

enter image description here

You can see too that the problems will automatically be listed in the problems tab! Which is cool!

Super cool! But i don’t use eslint

Typescript and TSLINT

If you are a typescript user and you use TSLINT!
Then we need to go to the global way! And that’s by creating a task!
Just like eslint did! (problemMatcher: $tsc) [you’ll get to know what that is just a bit bellow].

(Make sure to check TSLINT is deprecated title)!

I use a complete other language (c#, java, c++, php, python …)

Yup yup! We need a global way! And the global way is through creating a task!

Creating a task (The global way)

(Support all languages (to be configured for each))

We need to create a task!

The vscode documentation explains it pretty awesomely and in details!

https://code.visualstudio.com/docs/editor/tasks

Check the documentation!

Now in short! I would resume what a task is in:

A vscode tool and feature! That allow us to setup tasks based on tools and scripts and run them within vscode! Analyse there output within vscode! And activating and profiting from other vscode features! That includes Click link navigation on terminal! And problems listing on problem tab! Auto fixing and suggestions! Integration with the debugging tool! …etc! It depends on the task type!

enter image description here

A task get set through a setting file (task.json)! For a workspace or the whole user! (Some tasks types need to be set for only a workspace! They depends on the variables of a workspace)!

Also the task feature contains a lot of options and features! And is a big piece! For more just check the documentation!

Back to our problem!

We want linting of a whole project! And errors detection!

We need to have the errors listed on the problems tab! And preferably too with fixes suggestions!

All this gonna be done through a task.

Setting up the task! And core elements

Through vscode task features and integration! We need to configure it to allow good output! And integration with the problems tab!

The config will go as such:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "type": "npm",
      "script": "lint",
      "problemMatcher": ["$eslint-stylish"]
    }
  ]
}

(Here eslint through npm run lint)

The most important thing here to see! Is the type which determine the category and the task handling and launch setup! The script which define what get executed! And lastly and importantly problemMatcher!

For the whole tasks setting up! And options you can check the doc!

Here another example for typescript:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "type": "typescript",
      "tsconfig": "tsconfig.json",
      "problemMatcher": ["$tsc"],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

TSLINT is deprecated

Yo ! You just shown how, a line above! Yea there is something important!
We can see typescript problems through tsc compile process! Or Through TSLINT! TSLINT will support code style rules and so on! BUT mmmm TSLINT is deprecated! And ESLINT is taking on! And in simple words use Eslint! And so we can use Eslint for Typescript! And that can be more rich!

Check the link bellow from the official link:

https://code.visualstudio.com/api/advanced-topics/tslint-eslint-migration

And humor face: Don’t be affraid to do this

enter image description here

Already did!

Should i migrate Tslint to eslint

Another reason would be: TSLint is a linter that can only be used for TypeScript, while ESLint supports both JavaScript and TypeScript.

Reason for the choice and deprecation is:

In the TypeScript 2019 Roadmap, the TypeScript core team explains that ESLint has a more performant architecture than TSLint and that they will only be focusing on ESLint when providing editor linting integration for TypeScript.

Check it here and how to setup .eslintrc.js without the migration tool!

or https://www.npmjs.com/package/@typescript-eslint/eslint-plugin

Which in short would be like:

module.exports = {
  "parser": "@typescript-eslint/parser", // set eslint parser
   "parserOptions": {
       "ecmaVersion": 12, // latest ecma script features
       "sourceType": "module" // Allows for the use of imports
   },
   "plugins": [
       "@typescript-eslint"
   ],
  extends: [
    "plugin:@typescript-eslint/recommended" // Uses the recommended rules from the @typescript-eslint/eslint-plugin
  ],
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  }
};

And sure : npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

Make sure to use eslint --ext .js,.ts when executing eslint! Since by default eslint will only search for .js files.

Make sure to use the code styles versions that support typescript like this one for airbnb:

https://www.npmjs.com/package/eslint-config-airbnb-typescript

(The next section is the most important)!

Processing task output with problem matchers

https://code.visualstudio.com/docs/editor/tasks#_processing-task-output-with-problem-matchers

VS Code can process the output from a task with a problem matcher. Problem matchers scan the task output text for known warning or error strings, and report these inline in the editor and in the Problems panel. VS Code ships with several problem matchers ‘in-the-box’:

  • TypeScript: $tsc assumes that file names in the output are relative to the opened folder.
  • TypeScript Watch: $tsc-watch matches problems reported from the tsc compiler when executed in watch mode.
  • JSHint: $jshint assumes that file names are reported as an absolute path.
  • JSHint Stylish: $jshint-stylish assumes that file names are reported as an absolute path.
  • ESLint Compact: $eslint-compact assumes that file names in the output are relative to the opened folder.
  • ESLint Stylish: $eslint-stylish assumes that file names in the output are relative to the opened folder.
  • Go: $go matches problems reported from the go compiler. Assumes that file names are relative to the opened folder.
  • CSharp and VB Compiler: $mscompile assumes that file names are reported as an absolute path.
  • Lessc compiler: $lessc assumes that file names are reported as absolute path.
  • Node Sass compiler: $node-sass assumes that file names are reported as an absolute path.

OK but you said JAVA, C/C++, PHP, Python …
=> We need to write our own problemMatcher

C/C++ (GCC)

The c/c++ support in vscode is added through the official ms extension ms-vscode.cpptools

https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools

The extension provide $gcc problemMatcher!

A task will go as:

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "g++ build all",
      "command": "/usr/bin/g++",
      "args": ["${workspaceFolder}/src/*.cpp", "-o", "${workspaceFolder}/build"],
      "options": {
        "cwd": "/usr/bin"
      },
      "problemMatcher": ["$gcc"],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

Note that i just made the compilation to go for files in src (one level)

One can use cmake to build!

May like to check :
https://code.visualstudio.com/docs/cpp/config-linux#_build-helloworldcpp

Defining a problem matcher

You can check the doc section bellow:

https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher

An example for gcc was given for c/c++!
A compilation outcome will be like:

helloWorld.c:5:3: warning: implicit declaration of function ‘prinft’

We set a matcher by the following

{
  // The problem is owned by the cpp language service.
  "owner": "cpp",
  // The file name for reported problems is relative to the opened folder.
  "fileLocation": ["relative", "${workspaceFolder}"],
  // The actual pattern to match problems in the output.
  "pattern": {
    // The regular expression. Example to match: helloWorld.c:5:3: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
    "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
    // The first match group matches the file name which is relative.
    "file": 1,
    // The second match group matches the line on which the problem occurred.
    "line": 2,
    // The third match group matches the column at which the problem occurred.
    "column": 3,
    // The fourth match group matches the problem's severity. Can be ignored. Then all problems are captured as errors.
    "severity": 4,
    // The fifth match group matches the message.
    "message": 5
  }
}

Directly in the task config that can go as:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "build",
      "command": "g++",
      "args": ["${workspaceFolder}/src/*.cpp", "-o", "${workspaceFolder}/build"],
      "problemMatcher": {
        "owner": "cpp",
        "fileLocation": ["relative", "${workspaceFolder}"],
        "pattern": {
          "regexp": "^(.*):(\d+):(\d+):\s+(warning|error):\s+(.*)$",
          "file": 1,
          "line": 2,
          "column": 3,
          "severity": 4,
          "message": 5
        }
      }
    }
  ]
}

You can see how staight forward the setting is!
You can check the doc link above for more details!

Defining multiple line problem matcher

https://code.visualstudio.com/docs/editor/tasks#_defining-a-multiline-problem-matcher

Some tools spread problems found in a source file over several lines, especially if stylish reporters are used. An example is ESLint; in stylish mode it produces output like this:

test.js
  1:0   error  Missing "use strict" statement                 strict
✖ 1 problems (1 errors, 0 warnings)

I’ll not go about the details check the doc! it explains it well (check the loop property too!

{
  "owner": "javascript",
  "fileLocation": ["relative", "${workspaceFolder}"],
  "pattern": [
    {
      "regexp": "^([^\s].*)$",
      "file": 1
    },
    {
      "regexp": "^\s+(\d+):(\d+)\s+(error|warning|info)\s+(.*)\s\s+(.*)$",
      "line": 1,
      "column": 2,
      "severity": 3,
      "message": 4,
      "code": 5,
      "loop": true
    }
  ]
}

Modifying an existing problem matcher

https://code.visualstudio.com/docs/editor/tasks#_modifying-an-existing-problem-matcher

Simply check the doc!

JAVA

oK now we know, how to make problems matchers! We didn’t do java yet! So let’s do that for it! (Wait i just googled and here someone that did it)

{
    // compiles all files in the folder of the currently opened file
    "taskName": "javac all",
    "args": ["$env:CLASSPATH += ';${fileDirname}'; javac ${fileDirname}\*.java -Xlint"],
    "showOutput": "silent",
    "problemMatcher": {
        "owner": "java",
        "fileLocation": "absolute",
        "pattern": {
            "regexp": "^(.*):([0-9]+): (error|warning): (.*)$",
            "file": 1,
            "line": 2,
            "severity": 3,
            "message": 4
        }
    }
}

PHP

Here a php task too that use code sniff!

src (googling again): https://github.com/bmewburn/vscode-intelephense/issues/1102

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "PHP: CodeSniff Workspace",
      "type": "shell",
      "command": "${config:phpcs.executablePath}",
      "args": [
        "--standard=${config:phpcs.standard}",
        "--extensions=module,inc,install,php,theme,test,js,css",
        "--report=csv",
        "--basepath=${workspaceFolder}",
        "web/modules/custom"
      ],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": {
        "owner": "php",
        "fileLocation": [
          "relative",
          "${workspaceFolder}"
        ],
        "pattern": {
          "regexp": "^"(.*?)",(\d+),(\d+),(error|warning),"(.*)",.*$",
          "file": 1,
          "line": 2,
          "column": 3,
          "severity": 4,
          "message": 5
        }
      }
    }
  ]
}

Problem matcher and auto fixing

Ok so how the problem matcher make the auto fixing suggestions? The answer is it doesn’t! It can be clear! Or you may said at the first time you get to see the problem matcher, hey it may have a relation!

It isn’t! The languages support or linters extensions are what provide such a feature! And that through using vscode Action api!

Check

https://code.visualstudio.com/api/references/vscode-api#CodeAction

https://code.visualstudio.com/api/references/vscode-api#CodeActionKind

https://code.visualstudio.com/api/references/vscode-api#CodeActionProvider%3CT%3E

So simply: The problemMatcher set how the output of a task run is parsed and outputed on the problems tab!
And the languages support extension implement the auto fixes! Or linters! (Extensions) [I can make a play ground extension if i want]!

To note too that the yellow bulbe in the problems tab! Works and allow auto fixing! Because the problem matcher provide the line for the problem! That get mapped with the output of the extension fixing suggestions range! That get precised on the CodeActionProvider!

Is not possible right now, the VSCode team have a request for that feature that they are working in, so we must wait.

An alternative is to use a task runner to lint all errors in the project like the one created in this guide.

Не понимаю что не нравится VS Code (на скрине).
Браузер и сборщик ошибок не выдаёт, только редактор подсвечивает, но что не пойму.
На работу js-скрипта это не влияет, но сильно раздражает, когда один файл без причины подсвечен красным цветом.
Убрать эти неправленые ошибки тоже не выходит.
5dffc1e5cff79256402048.png


  • Вопрос задан

    более трёх лет назад

  • 407 просмотров

Version
Installs
Rating
OpenVSX Downloads

ErrorLens turbo-charges language diagnostic features by making diagnostics stand out more prominently, highlighting
the entire line wherever a diagnostic is generated by the language and also prints the message inline.

Demo image

Features

  • Highlight lines containing diagnostics
  • Append diagnostic as text to the end of the line
  • Show icons in gutter
  • Show message in status bar

Commands (11)

Command Description
errorLens.toggle Error Lens: Toggle (Enable/Disable) Everything (toggle global setting errorLens.enabled)
errorLens.toggleError Error Lens: Enable/Disable Errors in errorLens.enabledDiagnosticLevels setting.
errorLens.toggleWarning Error Lens: Enable/Disable Warnings in errorLens.enabledDiagnosticLevels setting.
errorLens.toggleInfo Error Lens: Enable/Disable Info in errorLens.enabledDiagnosticLevels setting.
errorLens.toggleHint Error Lens: Enable/Disable Hint in errorLens.enabledDiagnosticLevels setting.
errorLens.copyProblemMessage Error Lens: Copy problem message to the clipboard (at the active cursor).
errorLens.copyProblemCode Error Lens: Copy problem code to the clipboard (at the active cursor).
errorLens.findLinterRuleDefinition Error Lens: Search in local linter files (like .eslintrc.json) for the rule definition.
errorlens.toggleWorkspace Error Lens: Exclude/Include current workspace by fs path.
errorLens.searchForProblem Error Lens: Open problem in default browser (controlled by errorLens.searchForProblemQuery setting).
errorLens.disableLine Error Lens: Add a comment to disable line for linter rule.

Settings (55)

Error Lens extension settings start with errorLens.

Setting Default Description
enabled true Controls all decorations and features (except commands).
enabledInMergeConflict true Controls if decorations are shown if the editor has git merge conflict indicators <<<<<<< or ======= or >>>>>>>.
fontFamily «» Font family of inline message.
fontWeight «normal» Font weight of inline message. "normal" is alias for 400, "bold" is alias for 700).
fontStyleItalic false When enabled — shows inline message in italic font style.
fontSize «» Font size of inline message (CSS units).
margin «4ch» Distance between the last word on the line and the start of inline message (CSS units).
padding «» Padding of the inline message. Visible when #errorLens.messageBackgroundMode# is set to «message».
borderRadius «3px» Border radius of the inline message. Visible when #errorLens.messageBackgroundMode# is set to «message».
enabledDiagnosticLevels [«error», «warning», «info»] Customize which diagnostic levels(severity) to highlight.
messageTemplate «$message» Template used for all inline messages. Whitespace between items is important.
List of variables:
$message — diagnostic message text
$count — Number of diagnostics on the line
$severity — Severity prefix taken from #errorLens.severityText#
$source — Source of diagnostic e.g. «eslint»
$code — Code of the diagnostic
messageMaxChars 500 Cut off inline message if it’s longer than this value. (Improves performance when the diagnostic message is long). Set to 0 to disable inline message.
severityText [«ERROR», «WARNING», «INFO», «HINT»] Replaces $severity variable in #errorLens.messageTemplate#.
messageEnabled true Controls whether inline message is shown or not (Including background highlight).
messageBackgroundMode «line» Controls how inline message is highlighted in the editor (entire line / only message / none).
editorHoverPartsEnabled {«messageEnabled»:false, «sourceCodeEnabled»:false, «buttonsEnabled»:false} Controls which parts of the editor hover tooltip to show.
statusBarIconsEnabled false When enabled — shows highlighted error/warning icons in status bar.
statusBarIconsPriority -9000 Move status bar icons left or right by adjasting the number priority.
statusBarIconsAlignment «left» Choose on which side the icons status bar is on: left or right.
statusBarIconsUseBackground true When enabled — highlights status bar icons with background, when disabled — with foreground.
statusBarIconsAtZero «removeBackground» What to do when there are 0 errors/warnings — hide the item or strip its background color.
statusBarMessageEnabled false When enabled — shows message in status bar.
statusBarMessagePriority -10000 Move status bar message left or right by adjasting the number priority.
statusBarMessageAlignment «left» Choose on which side the message status bar is on: left or right.
statusBarColorsEnabled false When enabled — use message decoration foreground as color of Status Bar text.
statusBarMessageType «activeLine» Pick what to show in Status Bar: closest message or only message for the active line.
statusBarCommand «goToProblem» Pick command that activates on click for Status Bar.
statusBarMessageTemplate «» Template for status bar message. Whitespace between items is important.
List of variables:
$message — diagnostic message text
$count — Number of diagnostics on the line
$severity — Severity prefix taken from #errorLens.severityText#
$source — Source of diagnostic e.g. «eslint»
$code — Code of the diagnostic
exclude [] Specify messages that should not be highlighted (RegExp). Strings passed to the RegExp constructor: new RegExp(EXCLUDE_ITEM, 'i');
excludeBySource [] Specify source or source(code) pair that should not be highlighted. Examples: ["eslint"] or ["eslint(padded-blocks)"]
excludePatterns [] Exclude files by using glob pattern. Example ["**/*.{ts,js}"]
excludeWorkspaces [] Exclude workspaces by path.
disableLineComments {…} Used for errorLens.disableLine command that adds a comment disabling linter rule for a line.
lintFilePaths {…} Specify where to search for linter rule definitions by diagnostic source (glob for local linter files). node_modules folder is excluded.
searchForProblemQuery «https://duckduckgo.com/?q=$message» Pick query to open in default browser when searching for problem with errorLens.searchForProblem command.
light Specify color of decorations for when the light color theme is active.
delay 0 Delay (ms) before showing problem decorations (0 to disable). Minimum delay of 500 is enforced by the extension. New errors will be added with this delay; old errors that were fixed should disappear faster.
onSave false When enabled — updates decorations only on document save (manual).
onSaveTimeout 1000 Time period (ms) that used for showing decorations after the document save.
enableOnDiffView false Enable decorations when viewing a diff view in the editor (e.g. Git diff).
followCursor «allLines» Highlight only portion of the problems.
followCursorMore 0 Augments #errorLens.followCursor#.
Adds number of lines to top and bottom when #errorLens.followCursor# is set to activeLine.
Adds number of closest problems when #errorLens.followCursor# is closestProblem
gutterIconsEnabled false When enabled — shows gutter icons (In place of the debug breakpoint icon).
gutterIconsFollowCursorOverride true When enabled and #errorLens.followCursor# setting is not allLines, then gutter icons would be rendered for all problems. But line decorations (background, message) only for active line.
gutterIconSize «100%» Change gutter icon size. Examples: auto, contain, cover, 50%, 150%.
gutterIconSet «default» Change gutter icon style.
errorGutterIconPath «» Absolute path to error gutter icon.
warningGutterIconPath «» Absolute path to warning gutter icon.
infoGutterIconPath «» Absolute path to info gutter icon.
errorGutterIconColor «#e45454» Error color of circle gutter icon set.
warningGutterIconColor «#ff942f» Warning color of circle gutter icon set.
infoGutterIconColor «#00b7e4» Info color of circle gutter icon set.
removeLinebreaks true When enabled — replaces line breaks in inline diagnostic message with whitespaces.
replaceLinebreaksSymbol «⏎» Symbol to replace linebreaks. Requires enabling #errorLens.removeLinebreaks#.
scrollbarHackEnabled false When enabled — prevents showing horizontal scrollbar in editor (caused by inline decorations).

Colors (26)

Can be specified in settings.json (workbench.colorCustomizations section)

Color Dark Light HC Description
errorLens.errorBackground #e454541b #e4545420 #e454541b Background color of the entire line containing error.
errorLens.errorMessageBackground #e4545419 #e4545419 #e4545419 Background color of the error message.
errorLens.errorBackgroundLight #e4545420 #e4545420 #e4545420 Background color of the entire line containing error (Only in light themes).
errorLens.errorForeground #ff6464 #e45454 #ff6464 Text color used to highlight lines containing errors.
errorLens.errorForegroundLight #e45454 #e45454 #e45454 Text color used to highlight lines containing errors (Only in light themes).
errorLens.warningBackground #ff942f1b #ff942f20 #ff942f1b Background color used to highlight lines containing warnings.
errorLens.warningMessageBackground #ff942f19 #ff942f19 #ff942f19 Background color of the warning message.
errorLens.warningBackgroundLight #ff942f20 #ff942f20 #ff942f20 Background color used to highlight lines containing warnings (Only in light themes).
errorLens.warningForeground #fa973a #ff942f #fa973a Text color used to highlight lines containing warnings.
errorLens.warningForegroundLight #ff942f #ff942f #ff942f Text color used to highlight lines containing warnings (Only in light themes).
errorLens.infoBackground #00b7e420 #00b7e420 #00b7e420 Background color used to highlight lines containing info.
errorLens.infoMessageBackground #00b7e419 #00b7e419 #00b7e419 Background color of the info message.
errorLens.infoBackgroundLight #00b7e420 #00b7e420 #00b7e420 Background color used to highlight lines containing info (Only in light themes).
errorLens.infoForeground #00b7e4 #00b7e4 #00b7e4 Text color used to highlight lines containing info.
errorLens.infoForegroundLight #00b7e4 #00b7e4 #00b7e4 Text color used to highlight lines containing info (Only in light themes).
errorLens.hintBackground #17a2a220 #17a2a220 #17a2a220 Background color used to highlight lines containing hints.
errorLens.hintMessageBackground #17a2a219 #17a2a219 #17a2a219 Background color of the hint message.
errorLens.hintBackgroundLight #17a2a220 #17a2a220 #17a2a220 Background color used to highlight lines containing hints (Only in light themes).
errorLens.hintForeground #2faf64 #2faf64 #2faf64 Text color used to highlight lines containing hints.
errorLens.hintForegroundLight #2faf64 #2faf64 #2faf64 Text color used to highlight lines containing hints (Only in light themes).
errorLens.statusBarIconErrorForeground #ff6464 #e45454 #ff6464 Status bar icon item error color. Foreground is used when the errorLens.statusBarIconsUseBackground setting is disabled.
errorLens.statusBarIconWarningForeground #fa973a #ff942f #fa973a Status bar icon item error color. Foreground is used when the errorLens.statusBarIconsUseBackground setting is disabled.
errorLens.statusBarErrorForeground #ff6464 #e45454 #ff6464 Status bar item error color.
errorLens.statusBarWarningForeground #fa973a #ff942f #fa973a Status bar item warning color.
errorLens.statusBarInfoForeground #00b7e4 #00b7e4 #00b7e4 Status bar item info color.
errorLens.statusBarHintForeground #2faf64 #2faf64 #2faf64 Status bar item hint color.

Line highlighting depends on the "errorLens.messageBackgroundMode" setting.

#fff0 — Completely transparent color.

Upstream issues

Please upvote the following VS Code issues:

  • Api for editor insets
  • Access theme’s colors programmatically
  • When completing color keys in settings, fill in current value
  • Inline text adornments break word wrapping
  • OnClick event on Gutter
  • Support hover decorations over the line numbers i.e. gutter

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.

Debugging diagram

Debugger extensions

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

For debugging other languages and runtimes (including PHP, 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

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

Run and Debug icon

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

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

Simplified initial Run and Debug view

The top-level Run menu has the most common run and debug commands:

Run menu

Launch configurations

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

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

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

launch configuration

VS Code will try to automatically detect your debug environment, but if this fails, you will have to choose it manually:

debug environment selector

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

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

If you go back to the File Explorer view (⇧⌘E (Windows, Linux Ctrl+Shift+E)), you’ll see that VS Code has created a .vscode folder and added the launch.json file to your workspace.

launch.json in Explorer

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.

launch.json IntelliSense

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

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

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

launch json suggestions

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

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

Alternatively, you can run your configuration through the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) by filtering on Debug: Select and Start Debugging or typing 'debug ' and selecting the configuration you 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):

debug session

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 status

Debug actions

Once a debug session starts, the Debug toolbar will appear on the top of the editor.

Debug Actions

Action Explanation
Continue / Pause
F5
Continue: Resume normal program/script execution (up to the next breakpoint).
Pause: Inspect code executing at the current line and debug line-by-line.
Step Over
F10
Execute the next method as a single command without inspecting or following its component steps.
Step Into
F11
Enter the next method to follow its execution line-by-line.
Step Out
⇧F11 (Windows, Linux Shift+F11)
When inside a method or subroutine, return to the earlier execution context by completing remaining lines of the current method as though it were a single command.
Restart
⇧⌘F5 (Windows, Linux Ctrl+Shift+F5)
Terminate the current program execution and start debugging again using the current run configuration.
Stop
⇧F5 (Windows, Linux Shift+F5)
Terminate the current program execution.

Tip: Use the setting debug.toolBarLocation to control the location of the debug toolbar. It can be the default floating, docked to the Run and Debug view, or hidden. A floating debug toolbar can be dragged horizontally and also down to the editor area.

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.

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

If the debugger supports breaking on different kinds of errors or exceptions, those will 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.

Breakpoints

Optionally, breakpoints can be shown in the editor’s overview ruler by enabling the setting debug.showBreakpointsInOverviewRuler:

breakpoints in overview ruler

Logpoints

A Logpoint is a variant of a breakpoint that does not «break» into the debugger but instead logs a 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 (‘{}’).

Logpoints

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.

Debug Variables

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.

Debug Watch

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

Filtering in 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.

launch json suggestions

The following attributes are mandatory for every launch configuration:

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

Here are some optional attributes available to all launch configurations:

  • presentation — using the order, group, and hidden attributes in the presentation object, you can sort, group, and hide configurations and compounds in the Debug configuration dropdown and in the Debug quick pick.
  • preLaunchTask — to launch a task before the start of a debug session, set this attribute to the label of a task specified in tasks.json (in the workspace’s .vscode folder). Or, this can be set to ${defaultBuildTask} to use your default build task.
  • postDebugTask — to launch a task at the very end of a debug session, set this attribute to the name of a task specified in tasks.json (in the workspace’s .vscode folder).
  • internalConsoleOptions — this attribute controls the visibility of the Debug Console panel during a debugging session.
  • debugServerfor debug extension authors only: this attribute allows you to connect to a specified port instead of launching the debug adapter.
  • serverReadyAction — if you want to open a URL in a web browser whenever the program under debugging outputs a specific message to the debug console or integrated terminal. For details see section Automatically open a URI when debugging a server program below.

Many debuggers support some of the following attributes:

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

Variable substitution

VS Code makes commonly used paths and other values available as variables and supports variable substitution inside strings in launch.json. This means that you do not have to use absolute paths in debug configurations. For example, ${workspaceFolder} gives the root path of a workspace folder, ${file} the file open in the active editor, and ${env:Name} the environment variable ‘Name’. You can see a full list of predefined variables in the Variables Reference or by invoking IntelliSense inside the launch.json string attributes.

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

Platform-specific properties

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

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

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

Valid operating properties are "windows" for Windows, "linux" for Linux, and "osx" for macOS. 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:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/node_modules/gulp/bin/gulpfile.js",
      "stopOnEntry": true,
      "osx": {
        "stopOnEntry": false
      }
    }
  ]
}

Global launch configuration

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

"launch": {
    "version": "0.2.0",
    "configurations": [{
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "program": "${file}"
    }]
}

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.

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

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:

HitCount

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:
condition editing in breakpoint 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 context menu in the VARIABLES view. The Break on Value Change/Read/Access commands will add a data breakpoint that is hit when the value of the underlying variable changes/is read/is accessed. Data breakpoints are shown with a red hexagon in the BREAKPOINTS section.

Debug Console REPL

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

Debug Console

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:

  1. 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.

  2. 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, «<» or «>») as arguments.

Here’s an example launch.json configuration:

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

This approach requires that the «<» syntax is passed through the debugger extension and ends up unmodified in the Integrated Terminal.

Multi-target debugging

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.

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

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:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.send('Hello World!');
});

app.listen(3000, function() {
  console.log('Example app listening on port 3000!');
});

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:

{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "program": "${workspaceFolder}/app.js",

  "serverReadyAction": {
    "pattern": "listening on port ([0-9]+)",
    "uriFormat": "http://localhost:%s",
    "action": "openExternally"
  }
}

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

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

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

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

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.

The named launch configuration must be in the same file or folder as the one with the serverReadyAction.

Here the serverReadyAction feature in action:

Server ready feature in action

Next steps

To learn about VS Code’s Node.js debugging support, take a look at:

  • Node.js — Describes the Node.js debugger, which is included in VS Code.
  • TypeScript — The Node.js debugger also supports TypeScript debugging.

To see tutorials on the basics of Node.js debugging, check out these videos:

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

To learn about debugging support for other programming languages via VS Code extensions:

  • C++
  • Python
  • Java

To learn about VS Code’s task running support, go to:

  • Tasks — Describes how to run tasks with Gulp, Grunt, and Jake and how to show errors and warnings.

To write your own debugger extension, visit:

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

Common questions

What are the supported debugging scenarios?

Debugging of Node.js-based applications is supported on Linux, macOS, and Windows out of the box with VS Code. Many other scenarios are supported 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?

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

6/8/2023

Возможно, вам также будет интересно:

  • Как посмотреть ошибки в visual studio 2019
  • Как посмотреть ошибки opel astra gtc
  • Как посмотреть ошибки в ios
  • Как посмотреть ошибки occt обнаружены
  • Как посмотреть ошибки в explorer

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии