Отладка typescript в visual studio code
Окно консоли JavaScript можно использовать для взаимодействия и отладки приложений UWP, созданных с использованием JavaScript. Эти возможности поддерживаются для приложений UWP и приложений, созданных с помощью Средств для Apache Cordova в Visual Studio. Справочник по консольным командам см. в разделе JavaScript Console commands.
Окно консоли JavaScript предоставляет вам следующие возможности:
Просмотр и изменение значений локальных и глобальных переменных в запущенном приложении.
Просмотр визуализаторов объектов.
Запуск кода JavaScript, который выполняется в текущем контексте скрипта.
Просмотр ошибок и исключений JavaScript в дополнение к исключениям модели DOM и среды выполнения Windows.
Выполнение других задач, таких как очистка экрана. Полный список команд см. в разделе JavaScript Console commands .
Если окно консоли JavaScript закрыто, выберите Отладка> Windows > Консоль JavaScript , чтобы снова открыть его. Окно отображается только во время сеанса отладки скрипта.
С помощью окна консоли JavaScript можно взаимодействовать с приложением, не останавливая и не перезапуская отладчик. Дополнительные сведения см. в статье об обновлении приложения JavaScript. Сведения о других возможностях отладки JavaScript, таких как использование Проводника DOM и задание точек останова, см. в статьях Краткое руководство. Отладка файлов HTML и CSS и Отладка приложений в Visual Studio.
Отладка с использованием окна консоли JavaScript
Далее приведена процедура создания приложения FlipView и инструкции по интерактивной отладке ошибки кодирования JavaScript.
Здесь в качестве примера используется приложение UWP. Однако описываемые здесь функции консоли также применимы к приложениям, созданным с помощью инструментов Visual Studio для Apache Cordova.
Отладка кода JavaScript в приложении FlipView
Создайте новое решение в Visual Studio, выбрав Файл > Новый проект.
Выберите элементы JavaScript > Универсальная платформа Windows, а затем элемент Приложение WinJS.
Введите имя проекта, например FlipViewApp , и нажмите кнопку ОК , чтобы создать приложение.
В элементе BODY файла index.HTML замените существующий код HTML следующим кодом:
Откройте файл default.js и замените код следующим кодом JavaScript:
Если цель отладки еще не выбрана, на панели инструментов Отладка в раскрывающемся списке рядом с кнопкой Устройство выберите Локальный компьютер.
Нажмите клавишу F5, чтобы запустить отладчик.
Приложение выполняется, но изображения отсутствуют. Ошибки APPHOST в окне консоли JavaScript указывают на отсутствие изображений.
Во время выполнения приложения FlipView в строке ввода окна консоли (рядом с символом ">>") введите Data.items и нажмите клавишу ВВОД.
В окне консоли отображается визуализатор для объекта items . Это означает, что объект items создан и доступен в текущем контексте скрипта. В окне консоли можно щелкнуть узлы объекта, чтобы просмотреть значения свойств (или использовать клавиши со стрелками). Если щелкнуть объект items._data , как показано на рисунке, можно увидеть, что ссылки на источник изображений являются неправильными, как и ожидалось. Изображения по умолчанию (logo.jpg) все еще присутствуют в объекте, а отсутствующие изображения перемешаны с нужными.
Также обратите внимание на то, что в объекте items._data существует намного больше элементов, чем ожидалось.
В командной строке введите Data.items.push и нажмите клавишу ВВОД. В окне консоли отображается визуализатор для функции push , которая реализована в файле проекта Библиотека Windows для JavaScript (WinJS) . В этом приложении мы используем push для добавления надлежащих элементов. Выполнив небольшой анализ с помощью IntelliSense, можно установить, что следует использовать setAt для замены изображений по умолчанию.
Чтобы устранить эту проблему в интерактивном режиме без остановки сеанса отладки, откройте файл default.js и выберите этот код функции updateImages :
Скопируйте и вставьте этот код в строку ввода консоли JavaScript.
При вставке нескольких строк кода в строку ввода консоли JavaScript строка ввода консоли автоматически переключается в многострочный режим. Можно нажать сочетание клавиш Ctrl + Alt + M для включения и отключения многострочного режима. Чтобы выполнить скрипт в многострочном режиме, нажмите клавиши Ctrl + Ввод или выберите символ стрелки в правом нижнем углу окна. Дополнительные сведения см. в разделе Однострочный и многострочный режим в окне консоли JavaScript.
Исправьте вызовы функции push в командной строке, заменив pages.push на Data.items.setAt . Исправленный код должен выглядеть следующим образом.
Если необходимо использовать объект pages вместо Data.items , следует задать точку останова в коде для сохранения объекта pages в области.
Выберите символ зеленой стрелки, чтобы выполнить скрипт.
Нажмите клавиши CTRL+ALT+M, чтобы переключить строку ввода консоли в однострочный режим, а затем выберите Очистить входную строку (красный значок "X") чтобы удалить код из строки ввода.
Введите в командной строке Data.items.length = 3 и нажмите клавишу ВВОД. Это позволяет удалить лишние элементы данных.
Снова проверьте приложение — нужные изображения теперь отображаются на соответствующих страницах FlipView .
В обозревателе DOM отображается обновленный элемент DIV, и можно перейти в поддерево, чтобы найти нужные элементы IMG.
Остановите отладку, выбрав Отладка > Остановить отладку или нажав клавиши SHIFT+F5, а затем исправьте исходный код.
Полную страницу default.html с исправленным примером кода см. в разделе Отладка примера кода HTML, CSS и JavaScript.
Интерактивная отладка и режим приостановки выполнения
Можно использовать точки останова и пошаговое выполнение кода при использовании таких средств отладки JavaScript, как окно консоли JavaScript. Если программа, которая выполняется в отладчике, оказывается в точке останова, отладчик временно приостанавливает выполнение программы. Если выполнение приостановлено, программа переключается из режима выполнения в режим приостановки выполнения. Выполнение можно возобновить в любой момент.
Если программа находится в режиме приостановки выполнения, можно использовать окно консоли JavaScript для выполнения скриптов и команд, которые являются допустимыми в текущем контексте выполнения скрипта. При выполнении этой процедуры вы будете использовать исправленную версию приложения FlipView , созданную ранее, чтобы продемонстрировать использование режима приостановки выполнения.
Настройка точки останова и отладка приложения
В файле default.html приложения FlipView , созданного ранее, откройте контекстное меню функции updateImages() , а затем выберите Точка останова > Вставить точку останова.
На панели инструментов Отладка в раскрывающемся списке рядом с кнопкой Начать отладку выберите Локальный компьютер .
Выберите Отладка > Начать отладку или нажмите клавишу F5.
Приложение входит в режим приостановки выполнения, когда выполнение достигает функции updateImages() и текущая строка выполнения программы выделяется желтым.
Можно изменить значения переменных, чтобы немедленно изменить состояние программы, не завершая текущего сеанса отладки.
Введите в командной строке updateImages и нажмите клавишу ВВОД. В окне консоли отображается визуализатор для данной функции.
Выберите функцию в окне консоли, чтобы отобразить ее реализацию.
На следующем рисунке показано окно консоли на этом этапе.
Скопируйте одну строку функции из окна вывода в строку ввода и измените значение индекса на 3:
Нажмите клавишу ВВОД, чтобы выполнить эту строку кода.
Если требуется пошаговое выполнение кода по одной строке, нажмите клавишу F11 или нажмите клавишу F5, чтобы продолжить выполнение программы.
Нажмите клавишу F5, чтобы продолжить выполнение программы. Появляется приложение FlipView , и теперь на всех четырех страницах отображается одно из изображений, не заданных по умолчанию.
Чтобы вернуться в Visual Studio, нажмите клавишу F12 или сочетание клавиш Alt + Tab.
Однострочный и многострочный режим в окне консоли JavaScript
Строка ввода в окне консоли JavaScript поддерживает однострочный и многострочный режим. Процедура интерактивной отладки в этом разделе включает примеры использования обоих режимов. Можно нажать сочетание клавиш Ctrl + Alt + M для переключения между режимами.
Однострочный режим позволяет просматривать историю ввода. Для перемещения по истории ввода можно использовать клавиши со стрелкой вверх и стрелкой вниз. В однострочном режиме строка ввода очищается при выполнении скриптов. Чтобы выполнить скрипт в однострочном режиме, нажмите клавишу ВВОД.
В многострочном режиме строка ввода при выполнении скриптов не очищается. При переключении из многострочного режима в однострочный можно очистить строку ввода, нажав клавишу Очистить входную строку (красный значок "X"). Чтобы выполнить скрипт в многострочном режиме, нажмите клавиши Ctrl + Ввод или выберите символ стрелки в правом нижнем углу окна.
Переключение контекста выполнения скрипта
Окно консоли JavaScript позволяет одновременно взаимодействовать с одним контекстом выполнения, который представляет один экземпляр узла веб-платформы (WWAHost.exe). В некоторых сценариях приложение может запускать другой экземпляр узла, например при использовании iframe , контракта совместного доступа, рабочего веб-процесса или элемента управления WebView . Если выполняется другой экземпляр узла, можно выбрать другой контекст выполнения во время запуска приложения, выбрав контекст выполнения в списке Целевой объект .
На следующем рисунке показан список "Цель" в окне консоли JavaScript.
Вы также можете переключить контекст выполнения с помощью команды cd , однако вы должны знать имя другого контекста выполнения, а используемая вами ссылка должна находиться в области. Список Целевой объект предоставляет более удобный доступ к другим контекстам выполнения.
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers classes, modules, and interfaces to help you build robust components.
Install the TypeScript compiler
Visual Studio Code includes TypeScript language support but does not include the TypeScript compiler, tsc . You will need to install the TypeScript compiler either globally or in your workspace to transpile TypeScript source code to JavaScript ( tsc HelloWorld.ts ).
The easiest way to install TypeScript is through npm, the Node.js Package Manager. If you have npm installed, you can install TypeScript globally ( -g ) on your computer by:
You can test your install by checking the version.
Hello World
Let's start with a simple Hello World Node.js example. Create a new folder HelloWorld and launch VS Code.
From the File Explorer, create a new file called helloworld.ts .
Now add the following TypeScript code. You'll notice the TypeScript keyword let and the string type declaration.
To compile your TypeScript code, you can open the Integrated Terminal ( ⌃` (Windows, Linux Ctrl+` ) ) and type tsc helloworld.ts . This will compile and create a new helloworld.js JavaScript file.
If you have Node.js installed, you can run node helloworld.js .
If you open helloworld.js , you'll see that it doesn't look very different from helloworld.ts . The type information has been removed and let is now var .
IntelliSense
In VS Code, you can see that you get language features such as syntax highlighting and bracket matching. When you were typing in the editor, you may have noticed IntelliSense, the smart code completions and suggestions provided by VS Code and the TypeScript language server. Below you can see the methods of console
When you select a method, you then get parameter help and can always get hover information.
tsconfig.json
So far in this tutorial, you have been relying on the TypeScript compiler's default behavior to compile your TypeScript source code. You can modify the TypeScript compiler options by adding a tsconfig.json file that defines the TypeScript project settings such as the compiler options and the files that should be included.
Important: To use tsconfig.json for the rest of this tutorial, invoke tsc without input files. The TypeScript compiler knows to look at your tsconfig.json for project settings and compiler options.
Add a simple tsconfig.json which set the options to compile to ES5 and use CommonJS modules.
When editing tsconfig.json , IntelliSense ( ⌃Space (Windows, Linux Ctrl+Space ) ) will help you along the way.
By default, TypeScript includes all the .ts files in the current folder and subfolders if the files attribute isn't included, so we don't need to list helloworld.ts explicitly.
Change the build output
Having the generated JavaScript file in the same folder as the TypeScript source will quickly get cluttered on larger projects, so you can specify the output directory for the compiler with the outDir attribute.
Delete helloworld.js and run the command tsc with no options. You will see that helloworld.js is now placed in the out directory.
See Compiling TypeScript to learn about other features of the TypeScript language service and how to use tasks to run your builds directly from VS Code.
Error checking
TypeScript helps you avoid common programming mistakes through strong type checking. For example, if you assign a number to message , the TypeScript compiler will complain with 'error TS2322: Type '2' is not assignable to type 'string'. You can see type checking errors in VS Code both in the editor (red squiggles with hover information) and the Problems panel ( ⇧⌘M (Windows, Linux Ctrl+Shift+M ) ). The [ts] prefix lets you know this error is coming from the TypeScript language service.
Quick Fixes
The TypeScript language service has a powerful set of diagnostics to find common coding issues. For example, it can analyze your source code and detect unreachable code which is displayed as dimmed in the editor. If you hover over the line of source code, you'll see a hover explaining and if you place your cursor on the line, you'll get a Quick Fix lightbulb.
Clicking on the lightbulb or pressing ⌘. (Windows, Linux Ctrl+. ) brings up the Quick Fix menu where you can select the Remove unreachable code fix.
Debugging
VS Code has built-in support for TypeScript debugging. To support debugging TypeScript in combination with the executing JavaScript code, VS Code relies on source maps for the debugger to map between the original TypeScript source code and the running JavaScript. You can create source maps during the build by setting "sourceMap": true in your tsconfig.json .
Rebuild by running tsc and you should now have a helloworld.js.map in the out directory next to helloworld.js .
With helloworld.ts open in the editor, press F5 . If you have other debugger extensions installed, you need to select Node.js from the dropdown.
The debugger will start a session, run your code, and display the "Hello World" message in the Debug console panel.
In helloworld.ts , set a breakpoint by clicking on the left gutter of the editor. You will see a red circle if the breakpoint is set. Press F5 again. Execution will stop when the breakpoint is hit and you'll be able to see debugging information such as variable values and the call stack in the Run view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ).
See Debugging TypeScript to learn more about VS Code's built-in debugging support for TypeScript and how you can configure the debugger for your project scenarios.
Next steps
This tutorial was a quick introduction to using VS Code for TypeScript development. Read on to learn more about using VS Code's compiling and debugging support for TypeScript:
-
- Use VS Code's powerful task system for compiling TypeScript. - Configure the debugger for your TypeScript project.
Common questions
Cannot launch program because corresponding JavaScript cannot be found
You've likely not set "sourceMap": true in your tsconfig.json and the VS Code Node.js debugger can't map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.
Visual Studio Code supports TypeScript debugging through its built-in Node.js debugger and Edge and Chrome debugger.
JavaScript source map support
TypeScript debugging supports JavaScript source maps. To generate source maps for your TypeScript files, compile with the --sourcemap option or set the sourceMap property in the tsconfig.json file to true .
In-lined source maps (a source map where the content is stored as a data URL instead of a separate file) are also supported, although in-lined source is not yet supported.
For a simple example of source maps in action, see the TypeScript tutorial, which shows debugging a simple "Hello World" Node.js application using the following tsconfig.json and VS Code default Node.js debugging configuration.
For more advanced debugging scenarios, you can create your own debug configuration launch.json file. To see the default configuration, go to the Run view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) and press the gear icon or Create a launch.json link to Configure or Fix 'launch.json'.
This will create a launch.json file in a .vscode folder with default values detected in your project.
VS Code has determined the program to launch, helloworld.ts , included the build as a preLaunchTask , and told the debugger where to find the generated JavaScript files.
There is full IntelliSense with suggestions and information for launch.json to help you learn about other debug configuration options. You can also add new debug configurations to launch.json with the Add Configuration button in the lower right.
Also see Node.js Debugging for examples and further explanations.
Mapping the output location
If generated (transpiled) JavaScript files do not live next to their source, you can help the VS Code debugger locate them by setting the outFiles attribute in the launch configuration. Whenever you set a breakpoint in the original source, VS Code tries to find the generated source by searching the files specified by glob patterns in outFiles .
Client-side debugging
TypeScript is great for writing client-side code as well as Node.js applications and you can debug client-side source code with the built-in Edge and Chrome debugger.
We'll create a tiny web application to show client-side debugging in action.
Create a new folder HelloWeb and add three files: helloweb.ts , helloweb.html , and tsconfig.json with the following content"
Run tsc to build the app and then test by opening helloweb.html in your browser (you can right-click helloweb.html in the File Explorer and select Copy Path to paste into your browser).
In the Run view, press the gear icon to create a launch.json file selecting Edge: launch as the debugger, or Chrome if you prefer.
Update the launch.json to specify the local file URL to helloweb.html :
The Run view configuration dropdown will now show the new configuration Launch Edge against localhost. If you run that configuration, your browser will launch with your web page. Open helloweb.ts in the editor and click the left gutter to add a breakpoint (it will be displayed as a red circle). Press F5 to start the debug session, which launches the browser and hits your breakpoint in helloweb.ts .
Common questions
Cannot launch program because corresponding JavaScript cannot be found
You've likely not set "sourceMap": true in your tsconfig.json or outFiles in your launch.json and the VS Code Node.js debugger can't map your TypeScript source code to the running JavaScript. Turn on source maps and rebuild your project.
Visual Studio позволяет выполнять отладку кода JavaScript и TypeScript. Вы можете задавать и использовать точки останова, подключать отладчик, проверять значения переменных, просматривать стек вызовов и применять другие функции отладки.
Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. В зависимости от методов, используемых для разработки приложений, вам может потребоваться установить вместе с Visual Studio рабочую нагрузку Разработка Node.js.
Отладка серверного скрипта
Открыв проект в Visual Studio, откройте файл JavaScript с серверным скриптом (например, server.js) и щелкните в области слева, чтобы задать точку останова:
Точки останова — это один из самых простых и важных компонентов надежной отладки. Точка останова указывает, где Visual Studio следует приостановить выполнение кода, чтобы вы могли проверить значения переменных или поведение памяти либо выполнение ветви кода.
Чтобы запустить приложение, нажмите клавишу F5 (или выберите пункт меню Отладка > Начать отладку).
Выполнение отладчика прервется в установленной точке останова (текущий оператор выделяется желтым цветом). Теперь вы можете изучить состояние приложения, наводя указатель мыши на переменные в текущей области и используя окна отладчика, такие как Локальные и Контрольные значения.
Чтобы продолжить выполнение приложения, нажмите клавишу F5.
Если вы хотите использовать Средства Chrome для разработчиков (средства F12), нажмите клавишу F12. С их помощью можно изучить модель DOM и взаимодействовать с приложением с помощью консоли JavaScript.
Отладка клиентского скрипта
Подготовка приложения к отладке
Если для кода применена минификация или он создан в транспайлере, например в TypeScript или Babel, для оптимизации возможностей отладки следует применить сопоставления источника. Подключить отладчик к запущенному клиентскому скрипту вы сможете даже без сопоставлений источника. Но в этом случае вы сможете задавать и использовать точки останова только в файле с минифицированным или созданным в транспайлере кодом, но не в исходном файле кода. Например, в приложении Vue.js минифицированный скрипт передается в формате строки в инструкцию eval , и другого способа пошагового выполнения этого кода в отладчике Visual Studio, кроме сопоставлений источника, нет. В сложных сценариях отладки вы можете использовать также средства для разработчиков в Chrome или средства F12 для Microsoft Edge.
Сведения о создании сопоставителей с исходным кодом см. в разделе Создание сопоставлений источника для отладки.
Подготовка браузера к отладке
Для этого сценария используйте Microsoft Edge (Chromium), в настоящее время называемый Microsoft Edge Beta в IDE, или Chrome.
Для этого сценария используйте Chrome.
Закройте все окна целевого браузера.
Другие экземпляры браузера могут препятствовать его открытию при включенной отладке. (Работающие расширения браузера могут препятствовать полному режиму отладки, поэтому для обнаружения неожиданных экземпляров Chrome может понадобиться открыть диспетчер задач).
Для Microsoft Edge (Chromium) также отключите все экземпляры Chrome. Это дает лучшие результаты, поскольку оба браузера используют базу кода Chromium.
Запустите браузер с включенной отладкой.
Начиная с Visual Studio 2019 флаг --remote-debugging-port=9222 можно задать при запуске браузера, выбрав Просмотреть с помощью. > из панели инструментов Отладка, Добавить, а затем установив соответствующий флаг в поле Аргументы. Используйте другое понятное для браузера имя, например, Microsoft Edge с отладкой или Chrome с отладкой. Подробности см. в заметках о выпуске.
Также можно открыть команду Выполнить кнопки Пуск в Windows (щелкнуть правой кнопкой мыши команду Выполнить) и ввести следующую команду:
Щелкните правой кнопкой мыши кнопку Пуск Windows, выберите команду Выполнить и введите следующую команду :
Ваш браузер будет запущен в режиме отладки.
Приложение еще не запущено, поэтому вы видите пустую страницу браузера.
Подключение отладчика к сценарию на стороне клиента
Чтобы подключить отладчик из Visual Studio и использовать точки останова в коде на стороне клиента, необходимо правильно настроить процесс в отладчике. Ниже описывается один из способов.
Перейдите в Visual Studio, а затем установите точку останова в исходном коде, который может быть файлом JavaScript, TypeScript или JSX. (Выберите для точки останова строку кода, в которой допустимы точки останова, например оператор return или объявление var).
Чтобы найти конкретный код в транспонированном файле, используйте Ctrl+F (Изменить > Найти и заменить > Быстрый поиск).
Для кода на стороне клиента, чтобы попасть в точку останова в файле TypeScript, .vue или JSX, как правило, необходимо использовать сопоставитель с исходным кодом. Сопоставитель с исходным кодом следует правильно настроить, чтобы он поддерживал отладку в Visual Studio.
Выберите ваш целевой браузер в качестве целевого объекта отладки в Visual Studio, нажмите клавиши CTRL+F5 (Отладка > Запуск без отладки), чтобы запустить приложение в браузере.
Если вы создали конфигурацию браузера с понятным именем, выберите ее в качестве цели отладки.
Приложение откроется в новой вкладке браузера.
Выберите Отладка > Присоединение к процессу.
Начиная с Visual Studio 2017, после первого присоединения к процессу с помощью этих инструкций, дальнейшее присоединение можно выполнять с помощью команды Отладка > Повторно подключиться к процессу.
В диалоговом окне Присоединить к процессу получите отфильтрованный список экземпляров браузера для присоединения.
В Visual Studio 2019 выберите правильный отладчик для вашего целевого браузера, JavaScript (Chrome) или JavaScript (Microsoft Edge — Chromium) в поле Присоединить к, введите chrome или edge в поле фильтра, чтобы отфильтровать результаты поиска.
В Visual Studio 2017 выберите в поле Присоединить к элемент Код Webkit и введите chrome в поле фильтра, чтобы отфильтровать результаты поиска.
Выберите процесс браузера с соответствующим портом узла (localhost в этом примере) и нажмите кнопку Присоединить.
Порт (например 1337) также может отображаться в поле Заголовок, чтобы помочь выбрать правильный экземпляр браузера.
В следующем примере показано, как это выглядит в браузере Microsoft Edge (Chromium).
Определить, что отладчик присоединился правильно, можно по открытию проводника DOM и консоли JavaScript в Visual Studio. Эти средства отладки аналогичны инструментам Chrome для разработчиков и средствам F12 для Microsoft Edge.
Обновите страницу браузера, поскольку код с точкой останова возможно уже был выполнен. При необходимости выполните действия, приводящие к выполнению кода с точкой останова.
Когда отладчик приостановит выполнение, вы можете изучить состояние приложения, наводя указатель мыши на переменные и используя окна отладчика. Вы также можете выполнять пошаговую отладку кода (клавиши F5, F10 и F11). Дополнительные сведения об основных функциях отладки см. в разделе Первое знакомство с отладчиком.
В зависимости от типа приложения, выполненных ранее шагов и других факторов, таких как состояние браузера, вы можете попасть в точку останова транскомпилированного файла .js либо исходного файла. В любом случае вы можете выполнять пошаговую отладку кода и просматривать переменные.
Если вам нужно декомпозировать код в исходном файле TypeScript, JSX или .vue и вы не можете это сделать, убедитесь, что ваша среда настроена правильно, как описано в разделе Устранение неисправностей.
Если вам нужно декомпозировать код в файле с компиляцией в код на языке программирования JavaScript (например, app-bundle.js), но сделать это не удается, удалите файл сопоставления источника filename.js.map.
Устранение неполадок точек останова и сопоставителей с исходным кодом
Если вам нужно декомпозировать код в исходном файле TypeScript или JSX, но сделать это не удается, используйте Присоединить к процессу, чтобы подключить отладчик, как описано в предыдущих этапах. Убедитесь, что ваша среда настроена правильно:
Вы закрыли все экземпляры браузера, включая расширения Chrome (с помощью диспетчера задач) для запуска браузера в режиме отладки.
Либо, если вам нужно декомпозировать код в исходном файле (например app.tsx), но сделать это не удается, попробуйте использовать оператор debugger; в исходном файле или установите точки останова в инструментах для разработчиков в Chrome (или средства F12 для Microsoft Edge).
Создание сопоставлений источника для отладки
В Visual Studio можно использовать и создавать сопоставления источника для исходных файлов JavaScript. Такая возможность часто нужна, когда исходный код минифицирован или создан в транспайлере, например в TypeScript или Babel. Доступные варианты зависят от типа проекта.
Проект TypeScript в Visual Studio по умолчанию автоматически создает сопоставления источника. Дополнительные сведения см. в разделе Настройка сопоставлений источника с помощью файла tsconfig.json.
В проекте JavaScript сопоставления источника можно создать с помощью средства упаковки (например, webpack) и компилятора (например, TypeScript или Babel), которые вы можете добавить в проект. Вместе с компилятором TypeScript необходимо добавить еще и файл tsconfig.json и установить опцию компилятора sourceMap . Пример такой операции на основе базовой конфигурации webpack вы найдете в руководстве по созданию приложения Node.js с использованием React.
Если вы не знакомы с сопоставлениями источников, изучите эту вводную статью, прежде чем продолжать работу.
Чтобы настроить дополнительные параметры для сопоставлений источника, используйте файл tsconfig.json или параметры проекта для проекта TypeScript, но не оба метода сразу.
Чтобы включить отладку с помощью Visual Studio, необходимо убедиться в правильности ссылок на исходный файл в созданном сопоставителе с исходным кодом (может потребоваться тестирование). Например, если вы используете webpack, ссылки в файле сопоставителя с исходным кодом включают префикс webpack:/// , который не позволяет Visual Studio найти исходный файл TypeScript или JSX. В частности, при исправлении для отладки, ссылку на исходный файл (например, app.tsx) следует изменить с webpack:///./app.tsx на ./app.tsx, что включает отладку (путь относительно вашего исходного файла). В следующем примере показано, как настроить сопоставители с исходным кодом в webpack, который является одним из наиболее распространенных средств увязки, чтобы они работали с Visual Studio.
(Только для webpack) Если точка останова устанавливается в TypeScript файла JSX (а не в виде файла JavaScript), необходимо обновить конфигурацию webpack. Например, в файл webpack-config.js может потребоваться заменить следующий код:
Это настройка только для разработки, позволяющая отладку кода на стороне клиента в Visual Studio.
В сложных сценариях средства браузера (F12) иногда лучше подходят для отладки, так как для них не нужно выполнять изменения в пользовательских префиксах.
Настройка сопоставлений источника с помощью файла tsconfig.json
Если вы добавите в проект файл tsconfig.json, Visual Studio будет считать корневой каталог проектом TypeScript. Чтобы добавить файл, щелкните проект правой кнопкой мыши в обозревателе решений и последовательно выберите Добавить > Новый элемент > JSON-файл конфигурации TypeScript. Это действие добавит в проект файл tsconfig.json, аналогичный представленному ниже.
Параметры компилятора для tsconfig.json
- inlineSourceMap. Создает один общий файл с сопоставлениями источников, а не отдельный файл сопоставления для каждого исходного файла.
- inlineSources. Помещает исходный код в тот же файл вместе с сопоставлениями источников. Для этого режима также нужно настроить inlineSourceMap или sourceMap.
- mapRoot. Указывает расположение, из которого отладчику следует брать файлы сопоставления источника ( .map), вместо расположения по умолчанию. Используйте этот флаг, если во время выполнения файлы .map и файлы .js должны размещаться в разных каталогах. Указанное здесь расположение внедряется в сопоставление источника, чтобы указать для отладчика расположение файлов .map.
- sourceMap. Создает соответствующий файл .map.
- sourceRoot. Указывает расположение, из которого отладчику следует брать файлы TypeScript, вместо расположения по умолчанию. Используйте этот флаг, если в ходе время выполнения и разработки исходные файлы должны размещаться в разных каталогах. Указанное здесь расположение внедряется в сопоставление источника, чтобы указать для отладчика расположение исходных файлов.
Дополнительные сведения о параметрах компилятора вы найдете на странице с параметрами компилятора в справочнике по TypeScript.
Настройка сопоставителей с исходным кодом с помощью параметров проекта (TypeScript project)
Также вы можете настроить параметры сопоставления источника в свойствах проекта, щелкнув проект правой кнопкой мыши и выбрав Проект > Свойства > Сборка TypeScript > Отладка.
Здесь доступны следующие параметры проекта.
- Создать сопоставления источника (эквивалентно sourceMap в tsconfig.json). Создает соответствующий файл .map.
- Укажите корневой каталог сопоставлений источника (эквивалентно mapRoot в tsconfig.json). Указывает расположение, из которого отладчику следует брать файлы сопоставления, вместо автоматически созданного расположения. Используйте этот флаг, если во время выполнения файлы .map и файлы .js должны размещаться в разных каталогах. Указанное здесь расположение внедряется в сопоставление источника, чтобы указать для отладчика расположение файлов сопоставления.
- Укажите корневой каталог файлов TypeScript (эквивалентно sourceRoot в tsconfig.json). Указывает расположение, из которого отладчику следует брать файлы TypeScript, вместо расположения по умолчанию. Используйте этот флаг, если в ходе выполнения и разработки исходные файлы должны размещаться в разных каталогах. Указанное здесь расположение внедряется в сопоставление источника, чтобы указать для отладчика расположение исходных файлов.
Начиная с Visual Studio 2019, Visual Studio обеспечивает отладку только для Chrome и Microsoft Edge (Chromium).
Visual Studio поддерживает отладку только для браузеров Chrome и Internet Explorer.
Однако, вы не сможете автоматически использовать точки останова в файлах, созданных с синтаксисом Razor (cshtml, vbhtml). Для отладки файлов такого типа вы можете применить два следующих подхода.
Поместите инструкцию debugger; в той строке, где нужно прервать выполнение. Эта инструкция прерывает выполнение динамического скрипта и начинает отладку сразу же при его создании.
Загрузите страницу и откройте динамический документ в Visual Studio. Чтобы воспользоваться этим методом, нужно открыть динамический файл в процессе отладки, задать в нем точку останова и обновить страницу. В зависимости от выбранного браузера (Chrome или Internet Explorer) вы сможете найти этот файл с помощью следующих действий.
Для Chrome откройте пункты меню Обозреватель решений > Документы скриптов > [Имя_нужной_страницы] .
Для Microsoft Edge (Chromium) используйте ту же процедуру, что и для Chrome.
Для Internet Explorer откройте пункты меню Обозреватель решений > Документы скриптов > Windows Internet Explorer > [Имя_нужной_страницы] .
You can debug JavaScript and TypeScript code using Visual Studio. You can set and hit breakpoints, attach the debugger, inspect variables, view the call stack, and use other debugging features.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free. Depending on the type of app development you're doing, you may need to install the Node.js development workload with Visual Studio.
Debug server-side script
With your project open in Visual Studio, open a server-side JavaScript file (such as server.js), click in the gutter to the left gutter to set a breakpoint:
Breakpoints are the most basic and essential feature of reliable debugging. A breakpoint indicates where Visual Studio should suspend your running code so you can take a look at the values of variables, or the behavior of memory, or whether or not a branch of code is getting run.
To run your app, press F5 (Debug > Start Debugging).
The debugger pauses at the breakpoint you set (the current statement is marked in yellow). Now, you can inspect your app state by hovering over variables that are currently in scope, using debugger windows like the Locals and Watch windows.
Press F5 to continue the app.
If you want to use the Chrome Developer Tools or F12 Tools, press F12. You can use these tools to examine the DOM and interact with the app using the JavaScript Console.
Debug client-side script
Prepare your app for debugging
If your source is minified or created by a transpiler like TypeScript or Babel, the use of source maps is required for the best debugging experience. Without source maps, you can still attach the debugger to a running client-side script. However, you may only be able to set and hit breakpoints in the minified or transpiled file, not in the original source file. For example, in a Vue.js app, minified script gets passed as a string to an eval statement, and there is no way to step through this code effectively using the Visual Studio debugger, unless you use source maps. In complex debugging scenarios, you might also use Chrome Developer Tools or F12 Tools for Microsoft Edge instead.
For help to generate source maps, see Generate source maps for debugging.
Prepare the browser for debugging
For this scenario, use either Microsoft Edge (Chromium), currently named Microsoft Edge Beta in the IDE, or Chrome.
For this scenario, use Chrome.
Close all windows for the target browser.
Other browser instances can prevent the browser from opening with debugging enabled. (Browser extensions may be running and preventing full debug mode, so you may need to open Task Manager to find unexpected instances of Chrome.)
For Microsoft Edge (Chromium), also shut down all instances of Chrome. Because both browsers use the chromium code base, this gives the best results.
Start your browser with debugging enabled.
Starting in Visual Studio 2019, you can set the --remote-debugging-port=9222 flag at browser launch by selecting Browse With. > from the Debug toolbar, then choosing Add, and then setting the flag in the Arguments field. Use a different friendly name for the browser such as Edge with Debugging or Chrome with Debugging. For details, see the Release Notes.
Alternatively, open the Run command from the Windows Start button (right-click and choose Run), and enter the following command:
Open the Run command from the Windows Start button (right-click and choose Run), and enter the following command:
This starts your browser with debugging enabled.
The app is not yet running, so you get an empty browser page.
Attach the debugger to client-side script
To attach the debugger from Visual Studio and hit breakpoints in client-side code, the debugger needs help to identify the correct process. Here is one way to enable this.
Switch to Visual Studio and then set a breakpoint in your source code, which might be a JavaScript file, TypeScript file, or a JSX file. (Set the breakpoint in a line of code that allows breakpoints, such as a return statement or a var declaration.)
To find the specific code in a transpiled file, use Ctrl+F (Edit > Find and Replace > Quick Find).
For client-side code, to hit a breakpoint in a TypeScript file, .vue, or JSX file typically requires the use of source maps. A source map must be configured correctly to support debugging in Visual Studio.
Select your target browser as the debug target in Visual Studio, then press Ctrl+F5 (Debug > Start Without Debugging) to run the app in the browser.
If you created a browser configuration with a friendly name, choose that as your debug target.
The app opens in a new browser tab.
Choose Debug > Attach to Process.
Starting in Visual Studio 2017, once you attach to the process the first time by following these steps, you can quickly reattach to the same process by choosing Debug > Reattach to Process.
In the Attach to Process dialog box, get a filtered list of browser instances that you can attach to.
In Visual Studio 2019, choose the correct debugger for your target browser, JavaScript (Chrome) or JavaScript (Microsoft Edge - Chromium) in the Attach to field, type chrome or edge in the filter box to filter the search results.
In Visual Studio 2017, choose Webkit code in the Attach to field, type chrome in the filter box to filter the search results.
Select the browser process with the correct host port (localhost in this example), and select Attach.
The port (for example, 1337) may also appear in the Title field to help you select the correct browser instance.
The following example shows how this looks for the Microsoft Edge (Chromium) browser.
You know the debugger has attached correctly when the DOM Explorer and the JavaScript Console open in Visual Studio. These debugging tools are similar to Chrome Developer Tools and F12 Tools for Microsoft Edge.
If the debugger does not attach and you see the message "Failed to launch debug adapter" or "Unable to attach to the process. An operation is not legal in the current state.", use the Windows Task Manager to close all instances of the target browser before starting the browser in debugging mode. Browser extensions may be running and preventing full debug mode.
Because the code with the breakpoint may have already executed, refresh your browser page. If necessary, take action to cause the code with the breakpoint to execute.
While paused in the debugger, you can examine your app state by hovering over variables and using debugger windows. You can advance the debugger by stepping through code (F5, F10, and F11). For more information on basic debugging features, see First look at the debugger.
You may hit the breakpoint in either a transpiled .js file or source file, depending on your app type, which steps you followed previously, and other factors such as your browser state. Either way, you can step through code and examine variables.
If you need to break into code in a TypeScript, JSX, or .vue source file and are unable to do it, make sure that your environment is set up correctly, as described in the Troubleshooting section.
If you need to break into code in a transpiled JavaScript file (for example, app-bundle.js) and are unable to do it, remove the source map file, filename.js.map.
Troubleshooting breakpoints and source maps
If you need to break into code in a TypeScript or JSX source file and are unable to do it, use Attach to Process as described in the previous steps to attach the debugger. Make sure you that your environment is set up correctly:
You closed all browser instances, including Chrome extensions (using the Task Manager), so that you can run the browser in debug mode.
Make sure that your source map file includes the correct relative path to your source file and that it doesn't include unsupported prefixes such as webpack:///, which prevents the Visual Studio debugger from locating a source file. For example, a reference like webpack:///.app.tsx might be corrected to ./app.tsx. You can do this manually in the source map file (which is helpful for testing) or through a custom build configuration. For more information, see Generate source maps for debugging.
Alternatively, if you need to break into code in a source file (for example, app.tsx) and are unable to do it, try using the debugger; statement in the source file, or set breakpoints in the Chrome Developer Tools (or F12 Tools for Microsoft Edge) instead.
Generate source maps for debugging
Visual Studio has the capability to use and generate source maps on JavaScript source files. This is often required if your source is minified or created by a transpiler like TypeScript or Babel. The options available depend on the project type.
A TypeScript project in Visual Studio generates source maps for you by default. For more information, see Configure source maps using a tsconfig.json file.
In a JavaScript project, you can generate source maps using a bundler like webpack and a compiler like the TypeScript compiler (or Babel), which you can add to your project. For the TypeScript compiler, you must also add a tsconfig.json file and set the sourceMap compiler option. For an example that shows how to do this using a basic webpack configuration, see Create a Node.js app with React.
If you are new to source maps, please read Introduction to JavaScript Source Maps before continuing.
To configure advanced settings for source maps, use either a tsconfig.json or the project settings in a TypeScript project, but not both.
To enable debugging using Visual Studio, you need to make sure that the reference(s) to your source file in the generated source map are correct (this may require testing). For example, if you are using webpack, references in the source map file include the webpack:/// prefix, which prevents Visual Studio from finding a TypeScript or JSX source file. Specifically, when you correct this for debugging purposes, the reference to the source file (such as app.tsx), must be changed from something like webpack:///./app.tsx to something like ./app.tsx, which enables debugging (the path is relative to your source file). The following example shows how you can configure source maps in webpack, which is one of the most common bundlers, so that they work with Visual Studio.
(Webpack only) If you are setting the breakpoint in a TypeScript of JSX file (rather than a transpiled JavaScript file), you need to update your webpack configuration. For example, in webpack-config.js, you might need to replace the following code:
This is a development-only setting to enable debugging of client-side code in Visual Studio.
For complicated scenarios, the browser tools (F12) sometimes work best for debugging, because they don't require changes to custom prefixes.
Configure source maps using a tsconfig.json file
If you add a tsconfig.json file to your project, Visual Studio treats the directory root as a TypeScript project. To add the file, right-click your project in Solution Explorer, and then choose Add > New Item > TypeScript JSON Configuration File. A tsconfig.json file like the following gets added to your project.
Compiler options for tsconfig.json
- inlineSourceMap: Emit a single file with source maps instead of creating a separate source map for each source file.
- inlineSources: Emit the source alongside the source maps within a single file; requires inlineSourceMap or sourceMap to be set.
- mapRoot: Specifies the location where the debugger should find source map (.map) files instead of the default location. Use this flag if the run-time .map files need to be in a different location than the .js files. The location specified is embedded in the source map to direct the debugger to the location of the .map files.
- sourceMap: Generates a corresponding .map file.
- sourceRoot: Specifies the location where the debugger should find TypeScript files instead of the source locations. Use this flag if the run-time sources need to be in a different location than the location at design-time. The location specified is embedded in the source map to direct the debugger to where the source files are located.
For more details about the compiler options, check the page Compiler Options on the TypeScript Handbook.
Configure source maps using project settings (TypeScript project)
You can also configure the source map settings using project properties by right-clicking the project and then choosing Project > Properties > TypeScript Build > Debugging.
These project settings are available.
- Generate source maps (equivalent to sourceMap in tsconfig.json): Generates corresponding .map file.
- Specify root directory of source maps (equivalent to mapRoot in tsconfig.json): Specifies the location where the debugger should find map files instead of the generated locations. Use this flag if the run-time .map files need to be located in a different location than the .js files. The location specified is embedded in the source map to direct the debugger to where the map files are located.
- Specify root directory of TypeScript files (equivalent to sourceRoot in tsconfig.json): Specifies the location where the debugger should find TypeScript files instead of source locations. Use this flag if the run-time source files need to be in a different location than the location at design-time. The location specified is embedded in the source map to direct the debugger to where the source files are located.
Starting in Visual Studio 2019, Visual Studio provides debugging support for Chrome and Microsoft Edge (Chromium) only.
Visual Studio provides debugging support for Chrome and Internet Explorer only.
However, you cannot automatically hit breakpoints on files generated with Razor syntax (cshtml, vbhtml). There are two approaches you can use to debug this kind of file:
Place the debugger; statement where you want to break: This causes the dynamic script to stop execution and start debugging immediately while it is being created.
Load the page and open the dynamic document on Visual Studio: You'll need to open the dynamic file while debugging, set your breakpoint, and refresh the page for this method to work. Depending on whether you're using Chrome or Internet Explorer, you'll find the file using one of the following strategies:
For Chrome, go to Solution Explorer > Script Documents > YourPageName.
When using Chrome, you might get a message no source is available between tags. This is OK, just continue debugging.
For Microsoft Edge (Chromium), use the same procedure as Chrome.
For Internet Explorer, go to Solution Explorer > Script Documents > Windows Internet Explorer > YourPageName.
Читайте также: