Как использовать различные launch.json для дебагинга в visual studio code?
Если я уже выбрал node в дебагинге visual studio code, то как я могу сделать launch.json для php?
Вот на эту шестерёночку нужно нажать, чтобы настроить launch.json(чтобы работал xdebugдля какого-либо расширения файлов), а сейчас просто открывается launch.json для node
- Вопрос задан более трёх лет назад
- 1304 просмотра
Launch json visual studio code как настроить
1) Открываем Visual Studio Code
2) В Visual Studio Code нажимаем в меню File → Open Folder выбираем папку где распокавали проект
3) Нажимаем Run → Run Debugging или кнопку F5
Структура файлов:
D:/my_react_example1
index.html
my.js
.vscode
launch.json файл настройки для Visual Studio Code
План (8 шагов). Создаем новое приложение JavaScript в Visual Studio Code. Отладка приложения.
Шаг 1. Открываем Visual Studio Code
Если у вас не установлена Visual Studio Code , нужно установить Visual Studio Code . .
Открываем Visual Studio Code

Шаг 2. Создаем новую папку my_javascript_project1
Создаем новую папку my_javascript_project1 на диске D:
и в Visual Studio Code нажимаем File → Open Folder .
и выбираем эту папку D:/my_javascript_project1

Шаг 3. Создаем новый файл index.html внутри Visual Studio Code

Добавим код в
файл D:/My/ my.html
Сохраним файл, для этого нажимаем File → Save

Шаг 4. Создаем новый файл my.js внутри Visual Studio Code

Добавим код в
файл my.js
function calculate_sum(a, b)
<
// calculate sum
var sum = a + b;
Сохраним файл для этого нажимаем File → Save
Шаг 5. Запускаем проект в отладчике Run → Start Debugging (клавиша F5) и выбираем Chrome

Если в списке нет Chrome , тогда установим Chrome Debugger
Шаг 6. Установим Chrome Debugger

Шаг 7. Настройка файла launch.json (выбираем путь к запускаемому файлу)
Опять запускаем проект т.е. нажимаем Run → Start Debugging и выбираем Chrome .
Появится файл с настройками launch.json .
В параметре url напишем путь к запускаемому файлу.

Файл lanuch.json
<
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
«version» : «0.2.0» ,
«configurations» : [
<
«type» : «chrome» ,
«request» : «launch» ,
«name» : «Launch Chrome» ,
«url» : «$/index.html»
>
]
>
Сохраним файл, в меню нажимаем File → Save
Шаг 8. Ставим точки остановки (Breakpoints)
Поставим точки остановки в файле index.js .
Точки остановки ставятся нажатием клавиши F9 .

Запускаем программу в отладчике (debug). Нажимаем Run → Run Debugging или кнопку F5 .
Программа запущена и мы можем смотреть:
• WATCH (значение переменных)
• CALL STACK (стэк вызова функций)
• BREAKPOINTS (ставить, убирать точки остановки)

На заметку!
После нажатия клавиши F5 , в самый в первый раз отладчик не останавливается на точке остановки.
Отладчик останавливается на точке остановки, когда я нажимаю Restart .


На заметку! Чтобы увидеть окно WATCH , BREAKPOINTS , CALL STACK нужно нажать в меню View → Debug .

Visual Studio Code очень удобно использовать для отладки JavaScript , а так же чтобы видеть значения переменных.
Configure C/C++ debugging
A launch.json file is used to configure the debugger in Visual Studio Code.
Visual Studio Code generates a launch.json (under a .vscode folder in your project) with almost all of the required information. To get started with debugging you need to fill in the program field with the path to the executable you plan to debug. This must be specified for both the launch and attach (if you plan to attach to a running instance at any point) configurations.
The generated file contains two sections, one that configures debugging for launch and a second that configures debugging for attach.
Configure VS Code’s debugging behavior
Set or change the following options to control VS Code’s behavior during debugging:
program (required)
Specifies the full path to the executable the debugger will launch or attach to. The debugger requires this location in order to load debug symbols.
symbolSearchPath
Tells the Visual Studio Windows Debugger what paths to search for symbol (.pdb) files. Separate multiple paths with a semicolon. For example: «C:\\Symbols;C:\\SymbolDir2» .
requireExactSource
An optional flag that tells the Visual Studio Windows Debugger to require current source code to match the pdb.
additionalSOLibSearchPath
Tells GDB or LLDB what paths to search for .so files. Separate multiple paths with a semicolon. For example: «/Users/user/dir1;/Users/user/dir2» .
externalConsole
Used only when launching the debuggee. For attach , this parameter does not change the debuggee’s behavior.
- Windows: When set to true, it will spawn an external console. When set to false, it will use VS Code’s integratedTerminal.
- Linux: When set to true, it will notify VS Code to spawn an external console. When set to false, it will use VS Code’s integratedTerminal.
- macOS: When set to true, it will spawn an external console through lldb-mi . When set to false, the output can be seen in VS Code’s debugConsole. Due to limitations within lldb-mi , integratedTerminal support is not available.
avoidWindowsConsoleRedirection
In order to support VS Code’s Integrated Terminal with gdb on Windows, the extension adds console redirection commands to the debuggee’s arguments to have console input and output show up in the integrated terminal. Setting this option to true will disable it.
logging
Optional flags to determine what types of messages should be logged to the Debug Console.
- exceptions: Optional flag to determine whether exception messages should be logged to the Debug Console. Defaults to true.
- moduleLoad: Optional flag to determine whether module load events should be logged to the Debug Console. Defaults to true.
- programOutput: Optional flag to determine whether program output should be logged to the Debug Console. Defaults to true.
- engineLogging: Optional flag to determine whether diagnostic engine logs should be logged to the Debug Console. Defaults to false.
- trace: Optional flag to determine whether diagnostic adapter command tracing should be logged to the Debug Console. Defaults to false.
- traceResponse: Optional flag to determine whether diagnostic adapter command and response tracing should be logged to the Debug Console. Defaults to false.
visualizerFile
.natvis file to be used when debugging. See Create custom views of native objects for information on how to create Natvis files.
showDisplayString
When a visualizerFile is specified, showDisplayString will enable the display string. Turning on this option can cause slower performance during debugging.
Example:
"name": "C++ Launch (Windows)", "type": "cppvsdbg", "request": "launch", "program": "C:\\app1\\Debug\\app1.exe", "symbolSearchPath": "C:\\Symbols;C:\\SymbolDir2", "externalConsole": true, "logging": "moduleLoad": false, "trace": true >, "visualizerFile": "$/my.natvis", "showDisplayString": true >
Configure the target application
The following options enable you to modify the state of the target application when it is launched:
args
JSON array of command-line arguments to pass to the program when it is launched. Example [«arg1», «arg2»] . If you are escaping characters, you will need to double escape them. For example, [«»] will send to your application.
cwd
Sets the working directory of the application launched by the debugger.
environment
Environment variables to add to the environment for the program. Example: [ < "name": "config", "value": "Debug" >] , not [ < "config": "Debug" >] .
Example:
"name": "C++ Launch", "type": "cppdbg", "request": "launch", "program": "$/a.out", "args": ["arg1", "arg2"], "environment": [ "name": "config", "value": "Debug" >], "cwd": "$" >
Customizing GDB or LLDB
You can change the behavior of GDB or LLDB by setting the following options:
MIMode
Indicates the debugger that VS Code will connect to. Must be set to gdb or lldb . This is pre-configured on a per-operating system basis and can be changed as needed.
miDebuggerPath
The path to the debugger (such as gdb). When only the executable is specified, it will search the operating system’s PATH variable for a debugger (GDB on Linux and Windows, LLDB on OS X).
miDebuggerArgs
Additional arguments to pass to the debugger (such as gdb).
stopAtEntry
If set to true, the debugger should stop at the entry-point of the target (ignored on attach). Default value is false .
stopAtConnect
If set to true, the debugger should stop after connecting to the target. If set to false, the debugger will continue after connecting. Default value is false .
setupCommands
JSON array of commands to execute in order to set up the GDB or LLDB. Example: «setupCommands»: [ < "text": "target-run", "description": "run target", "ignoreFailures": false >] .
customLaunchSetupCommands
If provided, this replaces the default commands used to launch a target with some other commands. For example, this can be «-target-attach» in order to attach to a target process. An empty command list replaces the launch commands with nothing, which can be useful if the debugger is being provided launch options as command-line options. Example: «customLaunchSetupCommands»: [ < "text": "target-run", "description": "run target", "ignoreFailures": false >] .
launchCompleteCommand
The command to execute after the debugger is fully set up in order to cause the target process to run. Allowed values are «exec-run», «exec-continue», «None». The default value is «exec-run».
Example:
"name": "C++ Launch", "type": "cppdbg", "request": "launch", "program": "$/a.out", "stopAtEntry": false, "customLaunchSetupCommands": [ "text": "target-run", "description": "run target", "ignoreFailures": false > ], "launchCompleteCommand": "exec-run", "linux": "MIMode": "gdb", "miDebuggerPath": "/usr/bin/gdb" >, "osx": "MIMode": "lldb" >, "windows": "MIMode": "gdb", "miDebuggerPath": "C:\\MinGw\\bin\\gdb.exe" > >
symbolLoadInfo
- loadAll: If true, symbols for all libs will be loaded, otherwise no solib symbols will be loaded. Modified by ExceptionList. Default value is true.
- exceptionList: List of filenames (wildcards allowed) separated by semicolons ; . Modifies behavior of LoadAll. If LoadAll is true then don’t load symbols for libs that match any name in the list. Otherwise only load symbols for libs that match. Example: «foo.so;bar.so»
Debugging dump files
The C/C++ extension enables debugging dump files on Windows and core dump files Linux and OS X.
dumpPath
If you want to debug a Windows dump file, set this to the path to the dump file to start debugging in the launch configuration.
coreDumpPath
Full path to a core dump file to debug for the specified program. Set this to the path to the core dump file to start debugging in the launch configuration. Note: core dump debugging is not supported with MinGw.
Remote debugging or debugging with a local debugger server
miDebuggerServerAddress
Network address of the debugger server (for example, gdbserver) to connect to for remote debugging (example: localhost:1234 ).
debugServerPath
Full path to debug server to launch.
debugServerArgs
Arguments for the debugger server.
serverStarted
Server-started pattern to look for in the debug server output. Regular expressions are supported.
filterStdout
If set to true, search stdout stream for server-started pattern and log stdout to debug output. Default value is true .
filterStderr
If set to true, search stderr stream for server-started pattern and log stderr to debug output. Default value is false .
serverLaunchTimeout
Time in milliseconds, for the debugger to wait for the debugServer to start up. Default is 10000.
pipeTransport
For information about attaching to a remote process, such as debugging a process in a Docker container, see the Pipe transport settings article.
hardwareBreakpoints
If provided, this explicitly controls hardware breakpoint behavior for remote targets. If require is set to true, always use hardware breakpoints. Default value is false . limit is an optional limit on the number of available hardware breakpoints to use which is only enforced when require is true and limit is greater than 0. Defaults value is 0. Example: «hardwareBreakpoints»: < require: true, limit: 6 >.
Additional properties
processId
Defaults to $ which will display a list of available processes the debugger can attach to. We recommend that you leave this default, but the property can be explicitly set to a specific process ID for the debugger to attach to.
request
Indicates whether the configuration section is intended to launch the program or attach to an already running instance.
targetArchitecture
Deprecated This option is no longer needed as the target architecture is automatically detected.
type
Indicates the underlying debugger being used. Must be cppvsdbg when using the Visual Studio Windows debugger, and cppdbg when using GDB or LLDB. This is automatically set to the correct value when the launch.json file is created.
sourceFileMap
This allows mapping of the compile-time paths for source to local source locations. It is an object of key/value pairs and will resolve the first string-matched path. (example: «sourceFileMap»: < "/mnt/c": "c:\\" >will map any path returned by the debugger that begins with /mnt/c and convert it to c:\\ . You can have multiple mappings in the object but they will be handled in the order provided.)
Environment variable definitions file
An environment variable definitions file is a simple text file containing key-value pairs in the form of environment_variable=value , with # used for comments. Multiline values are not supported.
The cppvsdbg debugger configuration also contains an envFile property that allows you to easily set variables for debugging purposes.
project.env file:
# project.env # Example environment with key as 'MYENVRIONMENTPATH' and value as C:\\Users\\USERNAME\\Project MYENVRIONMENTPATH=C:\\Users\\USERNAME\\Project # Variables with spaces SPACED_OUT_PATH="C:\\This Has Spaces\\Project"
Symbol Options
The symbolOptions element allows customization of how the debugger searches for symbols. Example:
"symbolOptions": "searchPaths": [ "C:\\src\\MyOtherProject\\bin\\debug", "https://my-companies-symbols-server" ], "searchMicrosoftSymbolServer": true, "cachePath": "%TEMP%\\symcache", "moduleFilter": "mode": "loadAllButExcluded", "excludedModules": [ "DoNotLookForThisOne*.dll" ] > >
Properties
searchPaths: Array of symbol server URLs (example: https://msdl.microsoft.com/download/symbols) or directories (example: /build/symbols) to search for .pdb files. These directories will be searched in addition to the default locations — next to the module and the path where the pdb was originally dropped to.
searchMicrosoftSymbolServer: If true the Microsoft Symbol server (https://msdl.microsoft.com/download/symbols) is added to the symbols search path. If unspecified, this option defaults to false .
cachePath«: Directory where symbols downloaded from symbol servers should be cached. If unspecified, the debugger will default to %TEMP%\SymbolCache..
moduleFilter.mode: This value is either «loadAllButExcluded» or «loadOnlyIncluded» . In «loadAllButExcluded» mode, the debugger loads symbols for all modules unless the module is in the ‘excludedModules’ array. In «loadOnlyIncluded» mode, the debugger will not attempt to load symbols for ANY module unless it is in the ‘includedModules’ array, or it is included through the ‘includeSymbolsNextToModules’ setting.
Properties for «loadAllButExcluded» mode
moduleFilter.excludedModules: Array of modules that the debugger should NOT load symbols for. Wildcards (example: MyCompany.*.dll) are supported.
Properties for «loadOnlyIncluded» mode
moduleFilter.includedModules: Array of modules that the debugger should load symbols for. Wildcards (example: MyCompany.*.dll) are supported.
moduleFilter.includeSymbolsNextToModules: If true, for any module NOT in the ‘includedModules’ array, the debugger will still check next to the module itself and the launching executable, but it will not check paths on the symbol search list. This option defaults to ‘true’.
Файл launch.json для расширения DevTools
Visual Studio Code использует launch.json файл для определения конфигураций отладки. Чтобы использовать расширение DevTools, файл нужен только в том случае, launch.json если вы хотите использовать отладчик, а веб-страница должна работать на веб-сервере, а не только в локальной файловой системе. В большинстве случаев единственное, что вам нужно знать о содержимом файла, созданного launch.json средствами разработки (если вы решили использовать его), — это ввести нужный URL-адрес в «url» строке в нескольких местах. Прочтите эту статью, если вы хотите использовать пользовательские расширенные конфигурации отладки.
Если вы хотите использовать пользовательский интерфейс Visual Studio Code, например F5, для запуска вкладок DevTools вместе с режимом отладки, ваша открытая папка (рабочая область) должна содержать созданный в .vscode каталоге файл DevTools (совместимый с DevTools). launch.json
Сведения о launch.json формате файла приведены ниже. Обычно ничего не нужно изменять в файле, за исключением замены нескольких экземпляров строки URL-адреса, как описано в разделе Открытие инструментов разработки, нажав кнопку Запустить проект в разделе Открытие инструментов разработки и браузера DevTools.
Где строки имен отображаются в пользовательском интерфейсе
Строка «name» каждой конфигурации отладки заполняет раскрывающийся список в нескольких местах.
- Выберите Файл>Закрыть папку.
- Выберите Файл>Открыть последние> C:\Users\username\Documents\GitHub\Demos\demo-to-do\index.html , клонированные для шага 5. Клонирование репозитория демонстраций в разделе Установка расширения DevTools для Visual Studio Code. Предположим, что в каталоге .vscode нет launch.json файла.
- Выберите Панель > действий Microsoft Edge Tools> нажмите кнопку Создать launch.json.
- В Обозреватель панели > действий дважды щелкните index.html , чтобы открыть ее.
- Выберите Пункт Запуск и отладка> панели > действий, нажмите кнопку Запуск и отладка. На боковой панели Запуск и отладка в левом верхнем углу строки: Запуск Edge без головы, присоединение Средств разработки и Запуск Edge, а также присоединение средств разработки. В нижней части окна Visual Studio Code строка — Launch Edge Headless and attach DevTools. Ниже приведены имена составных конфигураций .json в файле, сообщающие отладчику Visual Studio Code открыть две вкладки Средства разработки или вкладку DevTools и внешний браузер:
"compounds": [ < "name": "Launch Edge Headless and attach DevTools", "configurations": [ "Launch Microsoft Edge in headless mode", "Open Edge DevTools" ] >, < "name": "Launch Edge and attach DevTools", "configurations": [ "Launch Microsoft Edge", "Open Edge DevTools" ] >]

В консоли отладки в правом нижнем углу строка — Запуск Microsoft Edge в режиме без головы. Это строка не о вкладке Edge DevTools , а о вкладке Edge DevTools: Browser . Это имя отдельной конфигурации, а не составной конфигурации:
"configurations": [ . < "type": "pwa-msedge", "name": "Launch Microsoft Edge in headless mode", "request": "launch", "runtimeArgs": [ "--headless", "--remote-debugging-port=9222" ], "url": "file://c:\\Users\\collabera\\Documents\\GitHub\\Demos\\demo-to-do\\index.html", "presentation": < "hidden": true >>,

Расположение файла launch.json
- В области launch.json Обозреватель Visual Studio Code файл помещается в папку .vscode в корне открывшейся папки.
- Для репозитория, например репозитория Demos, при открытии всей папки репозитория кнопка Создать launch.json создает \.vscode\launch.json файл рядом с корнем для всего каталога репозитория.
- Если открыть определенную папку меньшего размера, например \Demos\demo-to-do\ , кнопка Создать launch.json помещает launch.json файл только в эту папку.
Visual Studio Code использует launch.json файл для настройки и настройки отладчика. launch.json — это файл конфигурации отладчика. Этот файл также определяет, какой веб-браузер следует использовать в сочетании с отладчиком. Например, при тестировании веб-страницы, нажав кнопку на веб-странице, чтобы запустить код JavaScript, отладчик Visual Studio Code прослушивает браузер и выполняет шаги по коду JavaScript веб-страницы.
Ниже приведена launch.json копия после нажатия кнопки Создать launch.json в расширении.
По умолчанию изначально определены три конфигурации и два соединения :
- configurations — в пользовательском интерфейсе Visual Studio Code в пользовательском интерфейсе отладчика отображаются следующие имена конфигураций:
- Запуск Microsoft Edge — это конфигурация типа launch.
- Запуск Microsoft Edge в режиме без головы — это конфигурация типа launch.
- Open Edge DevTools — это конфигурация типа отладки (или типа присоединения).
- Запуск Edge без головы и подключение средств разработки
- Запуск Edge и присоединение средств разработки
Intellisense и автозавершение
Наведите указатель мыши на имя или значение JSON, чтобы отобразить подсказку:

Начните вводить двойные кавычки, чтобы просмотреть список автозаполнения доступных свойств и описаний JSON:

При сохранении файла обязательно укажите правильно сформированный КОД JSON, включая запятые.
Типы конфигурации: запуск и отладка
Эти два разных типа конфигураций определены в этом .json файле для отладчика Visual Studio Code.
Конфигурация
Следующие разделы launch.json файла относятся к версии 2.1.1 расширения в расположении установки по умолчанию для Visual Studio Code в Windows.
Конфигурация 1. Запуск Microsoft Edge
Это конфигурация типа launch browser. Эта конфигурация определяет компонент браузера, например .html файл для отображения, если в пользовательском интерфейсе не выбран параметр «Без головы «.
Это имя конфигурации не отображается непосредственно в пользовательском интерфейсе. Эта конфигурация используется составной конфигурацией ниже.
Конфигурация 2. Запуск Microsoft Edge в режиме без головы
Это конфигурация типа launch browser. Эта конфигурация управляет компонентом браузера, например .html файлом для отображения, если на странице Параметры инструментов разработки > edge выбран параметр «Без заголовка«, как это по умолчанию.
Это имя конфигурации Запуск Microsoft Edge в режиме без головы отображается в пользовательском интерфейсе, например на панели инструментов отладки и в консоли отладки. При запуске нескольких экземпляров число добавляется к дополнительным экземплярам в пользовательском интерфейсе, например запуск Microsoft Edge в режиме без головы 2. Эта конфигурация используется составной конфигурацией ниже.
Конфигурация 3. Открытие инструментов разработки Edge
Это конфигурация типа «присоединение отладчика». Эта конфигурация управляет вкладкой (панелью) Edge DevTools , например, каким .html файлом заполняется инструмент «Элементы «.
Это имя конфигурации не отображается непосредственно в пользовательском интерфейсе. Эта конфигурация используется составной конфигурацией ниже.
Составные конфигурации
launch.json Раздел compounds определяет составные конфигурации.
Каждая составная конфигурация относится к двум конфигурациям: одна — для открытия вкладки Edge DevTools в Visual Studio Code, а другая — для открытия вкладки Edge DevTools: Browser (иногда называется экранной трансляцией или браузером без головы) или вкладки Edge DevTools: Browser и всего окна браузера Microsoft Edge.
В области Средства Microsoft Edge в разделе Целевые объекты в правой части целевого объекта нажмите кнопку Переключить экранную трансляцию . Безголовая внедренная панель Edge DevTools: вкладка (панель) браузера закрывается или открывается.
В области Средства Microsoft Edge в разделе Целевые объекты в правой части целевого объекта нажмите кнопку Подключить и открыть инструменты Microsoft Edge .
Составная конфигурация 1: запуск Edge без головы и подключение средств разработки
Эта составная конфигурация запускает следующие компоненты:
- Вкладка (панель) Edge DevTools: Browser (панель) в Visual Studio Code. Это определяется конфигурацией с параметром name «Запуск Microsoft Edge в режиме без головы» выше.
- Вкладка (панель) Edge DevTools в Visual Studio Code. Это определяется конфигурацией с параметром name Open Edge DevTools выше.
Имя этой составной конфигурации , Запуск Edge Headless и attach DevTools, отображается на панели инструментов отладки Visual Studio Code.
Составная конфигурация 2. Запуск Edge и подключение средств разработки
Эта составная конфигурация запускает следующие компоненты:
- Вкладка (панель) Edge DevTools: Browser (панель) в Visual Studio Code. Это определяется конфигурацией с параметром name «Запуск Microsoft Edge» выше.
- Окно браузера Microsoft Edge. Это определяется конфигурацией с параметром name «Запуск Microsoft Edge» выше.
- Вкладка (панель) Edge DevTools в Visual Studio Code. Это определяется конфигурацией с параметром name Open Edge DevTools выше.
Имя этой составной конфигурации , Запуск Edge и присоединение DevTools, отображается в пользовательском интерфейсе на панели инструментов Отладка Visual Studio Code.
Добавление конфигураций
Вы можете определить собственные дополнительные конфигурации отладки. Нажмите кнопку Добавить конфигурацию .
См. также
- Откройте DevTools и браузер DevTools.
- Начало работы с расширением DevTools для Visual Studio Code
- Расширение Средств разработки Microsoft Edge для Visual Studio Code
launch.json для других платформ
- Настройка отладки C/C++ в документации по Visual Studio Code.
- Настройте отладчик в разделе Использование React в Visual Studio Code в документации по Visual Studio Code.
