Launch json visual studio code как настроить
Visual Studio Code отличный выбор для начинающего программиста, имеет необходимый минимум:
- неплохую документацию
- автодополнение кода (с использованием IntelliSense)
- подсветка синтаксиса
- встроенный отладчик
- расширение функционала за счет плагинов
- управление системой контроля версий git
- кроссплатформенный
- бесплатный, с открытым исходным кодом
Также редактор адаптирован для Веб-разработки и вполне подойдет для серьезных проектов как основной инструмент редактирования кода.
Установка¶
Linux¶
Для Linux существуют два типа пакетов, самых популярных форматов, rpm и deb.
Установка в Ubuntu/Debian:
Fedora > 22 версии:
После установки можно запустить редактор следующей командой:
Пакетный менеджер Nix работает на любом Linux дистрибутиве, содержит богатую базу уже готовых пакетов, в том числе и vscode.
Установка пакетного менеджера:
Плагины¶
Редактор имеет возможность расширения функционала за счет плагинов и удобный интерфейс их установки, доступный по нажатию кнопки:
Из списка можно выбрать любой плагин и установить, после чего он применит свои настройки к редактору.
Расширения можно искать введя название или ключевые слова в строке поиска, например Python .
Python¶
После установки плагина Python нам становятся доступны многие функции:
- Автодополнение кода
- Проверка синтаксиса
- Отладка
- Подсказки
- Переход к определению функции, класса и прочее
Автодополнение¶
Работает при наборе по нажатию Ctrl + Space .
Проверка синтаксиса¶
Показывает ошибки в коде:
Работает если установлены Python пакеты Pylint , Pep8 или Flake8 .
Отладка¶
Встроенный в редактор отладчик позволяет отлаживать код визуально, устанавливать точки останова мышкой и просматривать переменные в отдельном окне. Это похоже на отладку в различных IDE, таких как QtCreator или Wingware.
Также избавляет программиста писать мучительные строки типа printf или import pdb;pdb.set_trace(); .
Настройки¶
Настройки хранятся в формате JSON и доступны из меню File->Preferences->User Settings .
Шрифт¶
Шрифт задается в настройках File->Preferences->User Settings :
Автодополнение через ¶
Более привычно дополнять код по клавише . Для этого необходимо открыть настройки пользователя File->Preferences->User Settings и прописать опцию editor.tabCompletion :
Открываем командную строку Ctrl + Shift + P
Вводим команду Configure Language
Меняем локаль на нужную, например ru :
Цветовое оформление задается в настройках File->Preferences->Color Theme .
Умеет подсвечивать изменения в файлах с предыдущего коммита, выполнять команды git и отслеживать состояние, например какая текущая ветка.
Python скрипты¶
Visual Studio Code требует для отладки открывать не просто файл, а директорию. Это необходимо, чтобы в этом каталоге сохранить локальные настройки редактора. Такая директория будет считаться проектом для редактора.
Для примера, создадим директорию hello1 и откроем в редакторе File->Open Folder. .
Создадим в этой директории файл myapp.py :
Для запуска приложения, заходим в режим отладки по нажатию на кнопку:
Пока у нас нет никаких настроек отладки/запуска проекта, но при первом запуске редактор предложит их выбрать из существующих шаблонов.
Шаблон Python создает настройки в файле launch.json в локальной директории, которые выглядят примерно так:
Это универсальный шаблон, который добавляет несколько вариантов запуска приложений. Нас будет интересовать первый вариант Python , просто запускающий python файл.
Запущенное приложение останавливается на первой строчке, что позволяет нам продолжать выполнение программы по шагам.
После выполнения второй строки, интерпретатор выдаст ошибку ImportError: No module named pyramid.config . Это происходит из-за того что в нашем Python окружении не установлен модуль pyramid .
Решить эту проблему можно двумя способами:
Установить Pyramid в глобальное окружение.
Создать виртуальное окружение, установить в нем Pyramid и прописать его в настройках Visual Studio Code.
Создаем виртуальное окружение:
Прописываем путь до виртуального окружения в настройках проекта Visual Studio Code (файл launch.json ):
Добавим файл .gitignore :
Создаем первый коммит
Для создания коммита требуется ввести комментарий и нажать на кнопку в виде галочки.
Прописываем путь до гитхаба в нашем проекте, при помощи команды Git Easy:Add Orign
Отправляем изменения на GitHub , при помощи команды Git Easy:Push Current Branch to Origin
Для того чтобы проверка синтаксиса заработала, необходимо создать файл .vscode/settings.json и переопределить в нем глобальные настройки для нашего проекта:
Pyramid¶
Фреймворк Pyramid имеет несколько стартовых шаблонов, которые нужны для того, чтобы не начинать писать код с нуля. Рассмотрим как создать шаблон с БД sqlite + SQLAlchemy и настроить его в Visual Studio Code.
Для начала создадим директорию hello2 и виртуальное окружение hello2_env :
После установки Pyramid , в окружении появляется команда pcreate . С ее помощью создадим проект по шаблону:
Устанавливаем его как Python пакет:
Но так-как БД еще не создана, отображается страница с подсказкой как ее инициализировать:
Теперь мы увидим стартовую страницу шаблона alchemy .
Проект на пирамиде запускается при помощи утилиты pserve . Добавим конфигурацию для Pyramid в файл настроек launch.json , чтобы можно было запускать/отлаживать приложение из редактора:
Поставим точку останова в функции my_view в файле hello2/views/default.py .
JavaScript¶
© Copyright 2020, Кафедра Интеллектуальных Информационных Технологий ИнФО УрФУ. Created using Sphinx 1.7.6.
The launch.json file is used to configure the debugger in Visual Studio Code.
Visual Studio Code generates a launch.json 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:
Configure the target application
The following options enable you to modify the state of the target application when it is launched:
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.
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:
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:
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
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.
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
The cppvsdbg debugger configuration also contains an envFile property that allows you to easily set variables for debugging purposes.
project.env file:
Symbol Options
The symbolOptions element allows customization of how the debugger searches for symbols. Example:
Properties:
cachePath": Directory where symbols downloaded from symbol servers should be cached. If unspecified, the debugger will default to %TEMP%\SymbolCache..
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'.
Visual Studio knows how to run many different languages and codebases, but it doesn't know how to run everything. If you opened a code folder in Visual Studio, and Visual Studio knows how to run your code, you can run it right away without any additional configuration.
If the codebase uses custom build tools that Visual Studio doesn't recognize, you need to provide some configuration details to run and debug the code in Visual Studio. You instruct Visual Studio how to build your code by defining build tasks. You can create one or more build tasks to specify all the items a language needs to build and run its code. You can also create arbitrary tasks that can do nearly anything you want. For example, you can create a task to list the contents of a folder or to rename a file.
Customize your project-less codebase by using the following .json files:
File name | Purpose |
---|---|
tasks.vs.json | Specify custom build commands and compiler switches, and arbitrary (non-build related) tasks. Accessed via the Solution Explorer right-click menu item Configure Tasks. |
launch.vs.json | Specify command-line arguments for debugging. Accessed via the Solution Explorer right-click menu item Debug and Launch Settings. |
These .json files are located in a hidden folder called .vs in the root folder of your codebase. The tasks.vs.json and launch.vs.json files are created by Visual Studio on an as-needed basis when you choose either Configure Tasks or Debug and Launch Settings on a file or folder in Solution Explorer. These .json files are hidden because users generally don't want to check them into source control. However, if you want to be able to check them into source control, drag the files into the root of your codebase by using your file system, where they then are visible in Solution Explorer and to source control.
To view hidden files in Visual Studio, choose the Show All Files button on the Solution Explorer toolbar.
Define tasks with tasks.vs.json
You can automate build scripts or any other external operations on the files you have in your current workspace by running them as tasks directly in the IDE. You can configure a new task by right-clicking on a file or folder and selecting Configure Tasks.
This creates (or opens) the tasks.vs.json file in the .vs folder. You can define a build task or arbitrary task in this file, and then invoke it using the name you gave it from the Solution Explorer right-click menu.
Custom tasks can be added to individual files, or to all files of a specific type. For instance, NuGet package files can be configured to have a "Restore Packages" task, or all source files can be configured to have a static analysis task, such as a linter for all .js files.
Define custom build tasks
If your codebase uses custom build tools that Visual Studio doesn't recognize, then you cannot run and debug the code in Visual Studio until you complete some configuration steps. Visual Studio provides build tasks where you can tell Visual Studio how to build, rebuild, and clean your code. The tasks.vs.json build task file couples the Visual Studio inner development loop to the custom build tools used by your codebase.
For such a makefile that contains build, clean, and rebuild targets, you can define the following tasks.vs.json file. It contains three build tasks for building, rebuilding, and cleaning the codebase, using NMAKE as the build tool.
After you define build tasks in tasks.vs.json, additional right-click menu (context menu) items are added to the corresponding files in Solution Explorer. For this example, "build", "rebuild", and "clean" options are added to the context menu of any makefile files.
The commands appear in the context menu under the Configure Tasks command due to their contextType settings. "build", "rebuild", and "clean" are build commands, so they appear in the build section in the middle of the context menu.
When you select one of these options, the task executes. Output appears in the Output window, and build errors appear in the Error List.
Define arbitrary tasks
You can define arbitrary tasks in the tasks.vs.json file, to do just about anything you want. For example, you can define a task to display the name of the currently selected file in the Output window, or to list the files in a specified directory.
The following example shows a tasks.vs.json file that defines a single task. When invoked, the task displays the filename of the currently selected .js file.
- taskName specifies the name that appears in the right-click menu.
- appliesTo specifies which files the command can be performed on.
- The command property specifies the command to invoke. In this example, the COMSPEC environment variable is used to identify the command line interpreter, typically cmd.exe.
- The args property specifies the arguments to be passed to the invoked command.
- The $ macro retrieves the selected file in Solution Explorer.
After saving tasks.vs.json, you can right-click on any .js file in the folder and choose Echo filename. The file name is displayed in the Output window.
If your codebase doesn't contain a tasks.vs.json file, you can create one by choosing Configure Tasks from the right-click or context menu of a file in Solution Explorer.
The next example defines a task that lists the files and subfolders of the bin directory.
- $ is a custom macro that is first defined before the tasks block. It is then called in the args property.
This task applies to all files. When you open the context menu on any file in Solution Explorer, the task's name List Outputs appears at the bottom of the menu. When you choose List Outputs, the contents of the bin directory are listed in the Output window in Visual Studio.
Settings scope
Multiple tasks.vs.json files can exist at the root and subdirectories of a codebase. This design enables the flexibility to have different behavior in different subdirectories of the codebase. Visual Studio aggregates or overrides settings throughout the codebase, prioritizing files in the following order:
- Settings files in the root folder’s .vs directory.
- The directory where a setting is being computed.
- The current directory’s parent directory, all the way up to the root directory.
- Settings files in the root directory.
These aggregation rules apply to tasks.vs.json. For information on how settings in other file are aggregated, see the corresponding section for that file in this article.
Properties for tasks.vs.json
This section describes some of the properties you can specify in tasks.vs.json.
appliesTo
You can create tasks for any file or folder by specifying its name in the appliesTo field, for example "appliesTo": "hello.js" . The following file masks can be used as values:
File mask | Description |
---|---|
"*" | task is available to all files and folders in the workspace |
"*/" | task is available to all folders in the workspace |
"*.js" | task is available to all files with the extension .js in the workspace |
"/*.js" | task is available to all files with the extension .js in the root of the workspace |
"src/*/" | task is available to all subfolders of the src folder |
"makefile" | task is available to all makefile files in the workspace |
"/makefile" | task is available only to the makefile in the root of the workspace |
Macros for tasks.vs.json
Macro | Description |
---|---|
$> | Specifies any environment variable (for example, $, $ and so on) that is set for the developer command prompt. For more information, see Developer Command Prompt and Developer PowerShell. |
$ | The full path to the workspace folder (for example, C:\sources\hello) |
$ | The full path of the file or folder selected to run this task against (for example, C:\sources\hello\src\hello.js) |
$ | The relative path to the file or folder (for example, src\hello.js) |
$ | The name of the file without path or extension (for example, hello) |
$ | The full path to the file, excluding the filename (for example, C:\sources\hello\src) |
$ | The extension of the selected file (for example, .js) |
Configure debugging with launch.vs.json
To configure CMake projects for debugging, see Configure CMake debugging sessions.
To configure your codebase for debugging, in Solution Explorer choose the Debug and Launch Settings menu item from the right-click or context menu of your executable file.
In the Select a Debugger dialog box, choose an option, and then choose the Select button.
If the launch.vs.json file doesn't already exist, it is created.
Next, right-click on the executable file in Solution Explorer, and choose Set as Startup Item.
The executable is designated as the startup item for your codebase, and the debugging Start button's title changes to reflect the name of your executable.
When you choose F5, the debugger launches and stops at any breakpoint you may have already set. All the familiar debugger windows are available and functional.
For additional details about custom build and debug tasks in C++ open folder projects, see Open Folder support for C++ build systems in Visual Studio.
Specify arguments for debugging
You can specify command-line arguments to pass in for debugging in the launch.vs.json file. Add the arguments in the args array, as shown in the following example:
When you save this file, the name of the new configuration appears in the debug target drop-down list, and you can select it to start the debugger. You can create as many debug configurations as you like.
The configurations array property in launch.vs.json is read from two file locations—the root directory for the codebase, and the .vs directory. If there is a conflict, priority is given to the value in .vs\launch.vs.json.
Additional settings files
In addition to the three .json files described in this topic, Visual Studio also reads settings from some additional files, if they exist in your codebase.
.vscode\settings.json
Visual Studio reads limited settings from a file named settings.json, if it is in a directory named .vscode. This functionality is provided for codebases that have previously been developed in Visual Studio Code. Currently, the only setting that is read from .vscode\settings.json is files.exclude , which filters files visually in Solution Explorer and from some search tools.
You can have any number of .vscode\settings.json files in your codebase. Settings read from this file are applied to the parent directory of .vscode and all of its subdirectories.
.gitignore
.gitignore files are used to tell Git which files to ignore; that is, which files and directories you don't want to check in. .gitignore files are usually included as part of a codebase so that the settings can be shared with all developers of the codebase. Visual Studio reads patterns in .gitignore files to filter items visually and from some search tools.
Settings read from the .gitignore file are applied to its parent directory and all subdirectories.
Visual Studio поддерживает множество разных языков и баз кода, но не все существующие варианты. Если вы откроете в Visual Studio папку с кодом, который поддерживает Visual Studio, его можно выполнить немедленно и без дополнительных настроек.
Если в базе кода используются пользовательские средства сборки, которые не распознаются Visual Studio, для выполнения и отладки такого кода в Visual Studio требуются определенные сведения о конфигурации. Чтобы указать Visual Studio правила сборки вашего кода, определите задачи сборки. Создав одну или несколько задач сборки, вы сможете указать в них все элементы, которые потребуются для сборки и выполнения кода на определенном языке. Кроме того, можно создавать произвольные задачи с практически неограниченными возможностями. Например, с помощью задач можно вывести список содержимого папки или переименовать файл.
Чтобы настроить базу кода, не относящуюся к конкретному проекту, воспользуйтесь следующими файлами .json:
Имя файла | Цель |
---|---|
tasks.vs.json | Определяет настраиваемые команды сборки и параметры компилятора, а также произвольные (не имеющие отношения к сборке) задачи. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Настройка задач. |
launch.vs.json | Определяет аргументы командной строки для отладки. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Параметры отладки и запуска. |
Описанные файлы .json находятся в скрытой папке с именем .vs в корневой папке базы кода. Файлы tasks.vs.json и launch.vs.json создаются в среде Visual Studio по мере необходимости, то есть когда вы выбираете в обозревателе решений действия Настройка задач или Параметры отладки и запуска для файла или папки. Эти файлы .json скрыты, потому что пользователи обычно не добавляют их в систему управления версиями. Но если требуется возможность записать их в систему управления версиями, с помощью файловой системы перетащите файлы в корневую папку базы кода, где они будут видны в Обозревателе решений и в системе управления версиями.
Чтобы просмотреть скрытые папки в Visual Studio, нажмите кнопку Показать все файлы на панели инструментов обозревателя решений.
Определение задач в файле tasks.vs.json
Вы можете автоматизировать скрипты сборки и любые внешние операции с файлами, размещенными в текущей рабочей области, запуская их как задачи в интегрированной среде разработки. Чтобы настроить новую задачу, щелкните правой кнопкой мыши нужный файл или папку и выберите Настройка задач.
В среде разработки откроется (или будет создан, если его еще нет) файл tasks.vs.json в папке .vs. Можно определить в этом файле задачу сборки или произвольную задачу, а затем вызывать ее по имени в контекстном меню обозревателя решений.
Настраиваемые задачи можно размещать в отдельных файлах или во всех файлах определенного типа. Например, можно определить во всех файлах пакета NuGet задачу "Восстановить пакеты" или поместить во все файлы исходного кода задачу статического анализа, например анализатор кода для всех JS-файлов.
Определение настраиваемых задач сборки
Если в базе кода используются настраиваемые средства сборки, которые не распознаются в Visual Studio, вам не удастся выполнить и отладить код в Visual Studio без нескольких дополнительных настроек. Visual Studio поддерживает задачи сборки, в которых вы можете указать Visual Studio правила сборки, перестроения и очистки кода. Файл задачи сборки tasks.vs.json связывает внутренний цикл разработки Visual Studio с пользовательскими средствами сборки, применяемыми для базы кода.
Этот файл makefile содержит целевые объекты сборки, очистки и перестроения, и вы можете определить для него указанный ниже файл tasks.vs.json. Он содержит три задачи сборки (для сборки, перестроения и очистки), для которых применяется средство сборки NMAKE.
Когда вы определите в файле tasks.vs.json задачи сборки, в контекстном меню обозревателя решений для соответствующих файлов появятся дополнительные пункты. В нашем примере для всех файлов makefile в контекстное меню добавляются действия "Сборка", "Перестроить" и "Очистить".
Эти команды отображаются в контекстном меню в разделе Настройка задач, как указано для них в параметрах contextType . "Сборка", "перестроение" и "очистка" являются командами сборки, поэтому они отображаются в разделе сборки, в центре контекстного меню.
Если вы выберете любой из этих вариантов, будет выполнена соответствующая задача. Выходные данные отображаются в окне Вывод, а ошибки сборки — в окне Список ошибок.
Определение произвольных задач
Вы можете описать в файле tasks.vs.json произвольную задачу, которая предназначена для выполнения любого действия. Например, можно определить задачу для отображения имени файла, выбранного в окне вывода, или списка файлов в указанном каталоге.
Ниже представлен пример файла tasks.vs.json, который определяет одну задачу. При вызове этой задачи отображается имя выбранного файла .js.
- taskName определяет имя, отображаемое в контекстном меню.
- В appliesTo указывается, для каких файлов можно выполнить эту команду.
- Свойство command определяет вызываемую команду. В нашем примере в переменной среды COMSPEC задается интерпретатор командной строки, обычно это cmd.exe.
- В свойстве args задаются аргументы, которые будут переданы вызываемой команде.
- Макрос $ передает выбранный файл в обозреватель решений.
Сохранив файл tasks.vs.json, вы можете щелкнуть правой кнопкой мыши любой файл .js и выбрать команду Echo filename (Отобразить имя файла). Имя файла будет отображено в окне Вывод.
Если в базе кода нет файлов tasks.vs.json, вы можете создать такой файл с помощью команды Настройка задач в контекстном меню обозревателя решений. Эту команду также можно вызвать, щелкнув файл правой кнопки мыши.
В следующем примере определяется задача перечисления всех файлов и вложенных папок из каталога bin.
- Пользовательский макрос $ определяется перед блоком tasks . Затем он вызывается в свойстве args .
Эта задача применяется ко всем файлам. Открыв в обозревателе решений контекстное меню для любого файла, вы увидите в нижней части этого меню задачу с именем List Outputs (Перечислить выходные объекты). Если выбрать команду List Outputs (Перечислить выходные объекты), все содержимое каталога bin выводится в окне Вывод в Visual Studio.
Область действия параметров
В корневой папке и вложенных папках базы кода может быть несколько файлов tasks.vs.json. Такой подход позволяет гибко настраивать разные правила для разных каталогов в базе кода. Visual Studio объединяет или переопределяет параметры для разных разделов базы кода, используя следующий приоритет файлов:
- файлы параметров в каталоге .vs в корневой папке;
- каталог, для которого вычисляются параметры;
- родительский каталог текущего каталога (вплоть до корневого каталога);
- файлы параметров в корневом каталоге.
Эти правила агрегирования применяются к tasks.vs.json. Сведения о правилах агрегирования параметров для другого файла см. в посвященном ему разделе этой статьи.
Свойства для tasks.vs.json
В этом разделе описаны некоторые свойства, которые можно задать в файле tasks.vs.json.
appliesTo
Вы можете создать задачи для любого файла или папки, указав их имена в поле appliesTo , например так: "appliesTo": "hello.js" . В качестве значения можно использовать следующие маски файлов:
Маска файла | Описание |
---|---|
"*" | Задача доступна для всех файлов и папок в рабочей области. |
"*/" | Задача доступна для всех папок в рабочей области. |
"*.js" | Задача доступна для всех файлов с расширением JS в рабочей области. |
"/*.js" | Задача доступна для всех файлов с расширением JS в корневой папке рабочей области. |
"src/*/" | Задача доступна для всех подпапок в папке SRC. |
"makefile" | Задача доступна для всех файлов makefile в рабочей области. |
"/makefile" | Задача доступна только для файлов makefile в корневой папке рабочей области. |
Макросы для tasks.vs.json
Макрос | Описание |
---|---|
$> | Обозначает любую переменную среды (например, $, $ и т. д), которая определена для командной строки разработчика. Дополнительные сведения см. в статье о командной строке разработчика и PowerShell для разработчиков. |
$ | Полный путь к папке рабочей области (например, C:\sources\hello). |
$ | Полный путь к файлу или папке, для которой выполняется текущая задача (например, C:\sources\hello\src\hello.js). |
$ | Относительный путь к файлу или папке (например, src\hello.js). |
$ | Имя файла без пути или расширения (например, hello). |
$ | Полный путь к файлу без имени этого файла (например, C:\sources\hello\src). |
$ | Расширение выбранного файла (например, JS). |
Настройка отладки с помощью launch.vs.json
Сведения о настройке проектов CMake для отладки см. в разделе Настройка сеансов отладки CMake.
Чтобы настроить отладку для базы кода, выберите в контекстном меню обозревателя решений пункт Параметры отладки и запуска. Также его можно открыть, щелкнув исполняемый файл правой кнопкой мыши.
В диалоговом окне Выбор отладчика выберите нужный вариант и нажмите кнопку Выбрать.
Если файла launch.vs.json еще нет, он будет автоматически создан.
Теперь щелкните правой кнопкой мыши исполняемый файл в обозревателе решений и выберите команду Назначить автозапускаемым элементом.
Теперь этот исполняемый файл будет отмечен как автозапускаемый элемент и его имя отобразится на кнопке Пуск на панели инструментов отладки.
Нажатие клавиши F5 запускает отладчик, который будет останавливаться на всех заданных точках останова. Все обычные окна отладчика будут доступны и активны.
Дополнительные сведения о настраиваемых задачах сборки и отладки в проектах открытых папок C++ см. в статье Open Folder support for C++ build systems in Visual Studio (Поддержка открытых папок для систем сборки C++ в Visual Studio).
Указание аргументов для отладки
Вы можете указать в файле launch.vs.json аргументы командной строки, которые будут переданы для отладки. Добавьте нужные аргументы в массив args , как показано в следующем примере:
Когда вы сохраните этот файл, имя новой конфигурации отобразится в раскрывающемся списке для целевого объекта отладки. Вы можете выбрать ее, чтобы запустить отладчик. Можно создать любое количество конфигураций отладки.
Массив configurations , заданный в файле launch.vs.json, считывается из двух расположений — из корневого каталога базы кода и каталога .vs. Если между ними возникает конфликт, преимущество отдается значениям из .vs\launch.vs.json.
Дополнительные файлы параметров
Помимо трех файлов .json, которые описаны в этом разделе, Visual Studio считывает параметры из нескольких дополнительных файлов, если обнаружит их в базе кода.
.vscode\settings.json
Visual Studio считывает часть параметров из файла с именем settings.json, если он находится в каталоге с именем .vscode. Этот механизм применяется для поддержки баз кода, которые ранее разрабатывались в Visual Studio Code. Сейчас из файла .vscode\settings.json считывается только один параметр files.exclude , который определяет фильтрацию для отображения файлов в обозревателе решений и некоторых средствах поиска.
Вы можете определить в базе кода любое количество файлов .vscode\settings.json. Параметры из этого файла применяются к каталогу на один уровень выше соответствующего .vscode и ко всем его подкаталогам.
.gitignore
Файлы .gitignore позволяют указать Git, что некоторые файлы следует игнорировать. Здесь вы перечисляете файлы и каталоги, которые не нужно регистрировать в репозитории. Файлы .gitignore обычно включаются в базу кода, чтобы все разработчики базы кода могли использовать эти параметры. Visual Studio считывает шаблоны из файлов .gitignore для фильтрации элементов при отображении и в некоторых средствах поиска.
Параметры из файла .gitignore применяются к родительскому каталогу файла и всем его подкаталогам.
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.
It is helpful to first create a sample Node.js application before reading about debugging. Follow this guide to do a run-through with Node.js:
Once you are all set up this page will take you through the debugging scenarios we support.
Debug View
To bring up the Debug view, click on the Debugging icon in the View Bar on the side of VS Code.
The Debug view displays all information pertaining to debugging and has a top bar with debugging commands and configuration settings.
Launch Configurations
To debug your app in VS Code, you'll first need to setup your debugging launch configuration file - launch.json. Click on the Configure gear icon on the Debug view top bar, choose your debug environment and VS Code will generate a launch.json. Here is the one generated for Node.js debugging:
In VS Code we support launching your app in debug mode or attaching to an already running app. Depending on the request (attach or launch) different attributes are required and our launch.json validation and suggestions should help with that.
Review the generated values and make sure that they make sense for your project and debugging environment. You can add additional configurations to the launch.json (use hover and IntelliSense to help).
Select the configuration named Launch using the Configuration dropdown in the Debug view. Once you have your launch configuration set, start your debug session with kb(workbench.action.debug.start) .
To launch a task before the start of each debug session, set the preLaunchTask to the name of one of the tasks specified in tasks.json.
Breakpoints
Breakpoints can be toggled by clicking on the editor margin. Finer breakpoint control (enable/disable/reapply) can be done in the Debug view BREAKPOINTS section.
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 code that has not yet been executed. (For details see below under Node Debugging: Breakpoint Validation)
Data inspection
Variables can be inspected in the VARIABLES section of the Debug view or by hovering over their source in the editor. Variables and expression evaluation is relative to the selected stack frame in the CALL STACK section.
Variables and expressions can also be evaluated and watched in the Debug view WATCH section.
Debug Console
Expressions can be evaluated in the Debug Console. To open the Debug Console use the Open Console action at the top of the Debug pane or using the Command Palette.
Debug actions
Once a debug session starts, the Debug actions pane will appear on the top of the editor.
- Continue / Pause kb(workbench.action.debug.continue)
- Step Over kb(workbench.action.debug.stepOver)
- Step Into kb(workbench.action.debug.stepInto)
- Step Out kb(workbench.action.debug.stepOut)
- Restart kb(workbench.action.debug.restart)
- Stop kb(workbench.action.debug.stop)
Node Debugging
Node Console
By default node debug sessions launch the target in the internal VS Code Debug Console. Since the Debug Console does not support programs that need to read input from the console, you can enable an external, native console by setting the attribute externalConsole to true in your launch configuration.
Breakpoint Validation
For performance reasons Node.js parses the functions inside JavaScript files lazily on first access. As a consequence, breakpoints don't work in source code areas that haven't been seen (parsed) by Node.js.
Since this behavior is not ideal for debugging, VS Code passes the --nolazy option to Node.js automatically. This prevents the delayed parsing and ensures that breakpoints can be validated before running the code (so they no longer "jump").
Since the --nolazy option might increase the start-up time of the debug target significantly, you can easily opt out by passing a --lazy as a runtimeArgs attribute.
When doing so you will find that some of your breakpoints don't "stick" to the line requested but instead "jump" for the next possible line in already-parsed code. To avoid confusion, VS Code always shows breakpoints at the location where Node.js thinks the breakpoint is. In the breakpoint section, these breakpoints are shown with an arrow between requested and actual line number:
This breakpoint validation occurs when a session starts and the breakpoints are registered with Node.js, or when a session is already running and a new breakpoint is set. In this case, the breakpoint may "jump" to a different location. After Node.js has parsed all the code (e.g. by running through it), breakpoints can be easily re-applied to the requested locations with the Reapply button in the breakpoint section header. This should make the breakpoints "jump back" to the requested location.
JavaScript Source Maps
The Node.js debugger of VS Code supports JavaScript Source Maps which help debugging of transpiled languages, e.g. TypeScript or minified/uglified JavaScript. With source maps it is possible to single step through or set breakpoints in the original source. The source map feature is enabled by setting the sourceMaps attribute to true in the launch configuration. In addition, you can specify a source file (e.g. app.ts) with the program attribute. If the generated (transpiled) JavaScript files do not live next to their source but in a separate directory, you can help the VS Code debugger locate them by setting the outDir attribute. Whenever you set a breakpoint in the original source, VS Code tries to find the generated source, and the associated source map, in the outDir directory.
Since source maps are not automatically created, you must configure the TypeScript compiler to create them:
This is the corresponding launch configuration for a TypeScript program:
Source maps can be generated with two kinds of inlining:
- 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).
VS Code supports inlined source maps but not inlined source.
Attaching VS Code to Node
If you want to attach the VS Code debugger to a Node.js program, launch Node.js as follows:
With the --debug-brk option Node.js stops on the first line of the program. The corresponding launch configuration looks like this:
Mono Debugging
- On OS X: brew install mono
- On Linux: sudo apt-get install mono-complete
If you want to attach the VS Code debugger to a Mono program, pass these additional arguments to the Mono runtime:
The corresponding launch configuration looks like this:
Next Steps
In case, you didn't already read the Node.js section, take a look at:
-
- End to end Node scenario with a sample application
To learn about VS Code's task running support, go to:
-
- Running tasks with Gulp, Grunt and Jake. Showing Errors and Warnings
To write your own debugger extension, visit:
-
- Steps to create a VS Code debug extension starting from a mock sample
Common Questions
Q: What are the supported debugging scenarios?
Q: Why can’t I remote debug my app?
A: Currently we support local debugging only. This is a known limitation. If that’s something you care about, please let us know!
Q: I do not see any launch configurations in the debug view drop down, what is wrong?
A: The most common problem is that you did not set up launch.json yet or there is a syntax error in the launch.json file.
Q: What Node.js version is required for Node.js debugging?
A: Version 0.12.x is recommended, though most functionality is supported in 0.10.x as well (except break on unhandled exceptions).
Q: Is Mono debugging supported on Windows?
A: No. Currently Mono debugging is only supported on Mac and Linux.
Читайте также: