Visual studio code расширение для отладки
Office надстройки, работающие на Windows, могут использовать расширение отладки Office надстройки в Visual Studio Code для отладки устаревшая версия Microsoft Edge с исходным временем запуска WebView (EdgeHTML).
Эта статья применяется только Office запуска надстройки в исходном времени запуска WebView (EdgeHTML), как это объясняется в Браузерах, используемых Office надстройки. Инструкции по отладки Visual Studio кода Microsoft Edge webView2 (Chromium основе) см. в Microsoft Office расширение надстройки для Visual Studio Code.
Если вы не можете или не хотите отлаговку с помощью средств, встроенных в Visual Studio Code; или вы столкнулись с проблемой, которая возникает только при запуске надстройки за пределами Visual Studio Code, вы можете отлаговить время работы Edge Legacy (EdgeHTML), используя средства разработчика Edge Legacy, как описано в надстройке Debug с помощью средств разработчика в устаревшая версия Microsoft Edge.
Это динамический режим отладки, в нем можно устанавливать точки останова во время выполнения кода. Вы можете видеть изменения в коде сразу же, когда отладка присоединена, все без потери сеанса отладки. Изменения кода также сохраняются, поэтому вы можете видеть результаты нескольких изменений в коде. Работа этого расширения показана на следующем рисунке.
Предварительные требования
Установка и использование отладчика
Эти инструкции предполагают, что вы имеете опыт использования командной строки, понимаете базовый JavaScript и создали проект Office надстройки перед использованием генератора Yeoman для Office надстройки. Если вы еще не сделали этого раньше, подумайте о посещении одного из наших учебников, например Excel Office надстройки.
Первый шаг зависит от проекта и от порядка его создания.
- Если вы хотите создать проект, чтобы поэкспериментировать с отладкой в Visual Studio Code, используйте генератор Yeoman для надстроек Office. Для этого используйте любое руководство по началу работы, например Начало работы с надстройками Outlook.
- Если нужно отладить существующий проект, созданный с помощью Yo Office, перейдите к следующем шагу.
- Если вы хотите отлажен существующий проект, который не был создан с помощью Yo Office, выполнить процедуру в приложении, а затем вернуться к следующему шагу этой процедуры.
Откройте VS Code, откройте проект в этом решении.
Находясь в коде VS, нажмите клавиши CTRL+SHIFT+X, чтобы открыть меню расширений. Поиск расширения "Microsoft Office надстройки Debugger" и установка его.
Выберите Просмотр > Выполнить или нажмите клавиши CTRL+SHIFT+D, чтобы переключить представление отладки.
Из параметров RUN и DEBUG выберите параметр Edge Legacy для вашего хост-приложения, например Outlook Desktop (Edge Legacy). Чтобы начать отладку, нажмите F5 или выберите Выполнить > Начать отладку в меню. Это действие автоматически запускает локальный сервер в окне Node для размещения вашей надстройки, а затем автоматически открывает ведущее приложение, например Excel или Word. Это может занять несколько секунд.
WebView Stop On Load. Чтобы отладить webView, VS Code к экземпляру WebView с помощью расширения Microsoft Debugger for Edge и нажмите кнопку ОК для продолжения. Чтобы этот диалоговое окно не появлялись в будущем, нажмите кнопку Отмена.
Нажмите ОК.
После нажатия кнопки Отмена диалоговое окно не будет отображаться в процессе работы с этим экземпляром надстройки. Однако при перезапуске надстройки диалоговое окно снова появится.
Установите точку разлома в файле области задач проекта. Чтобы установить точки останова в Visual Studio Code, наведите указатель мыши на строку кода выберите появившийся красный кружок.
Запустите в надстройке функциональность, которая вызывает строки с точками останова. Вы увидите, что достигнуты точки останова, и можно изучить локальные переменные.
Точки останова в вызовах Office.initialize или Office.onReady игнорируются. Дополнительные сведения об этих методах см. в статье Инициализация надстройки Office.
Лучший способ остановить сеанс отладки — нажать клавиши SHIFT+F5 или выбрать Выполнить > Остановить отладку в меню. Это действие должно закрыть окно сервера Node и попытаться закрыть ведущее приложение, но в ведущем приложении появится запрос о необходимости сохранения документа. Сделайте соответствующий выбор и позвольте закрыть ведущее приложение. Избегайте закрытия окна Node или ведущего приложения вручную. Это может привести к ошибкам, особенно при многократной остановке и запуске сеансов отладки.
Если отладка перестает работать (например, если игнорируются точки останова), остановите отладку. Затем при необходимости закройте все окна ведущего приложения и окно Node. Наконец, закройте Visual Studio Code и снова откройте его.
Приложение
Если проект не был создан с помощью Yo Office, нужно создать конфигурацию отладки для Visual Studio Code.
Создайте файл с именем launch.json в папке проекта \.vscode , если такого файла там нет.
Убедитесь, что в файле есть массив configurations . Ниже приведен простой пример launch.json .
Добавьте следующий объект в массив configurations .
Замените местообладатель HOST во всех трех местах и на имя приложения Office, в которое выполняется надстройка; например, Outlook или Word .
Debug your JavaScript code in the Chrome browser, or any other target that supports the Chrome Debugger protocol.
:rotating_light: Important
This extension has been deprecated as Visual Studio Code now has a bundled JavaScript Debugger that covers the same functionality. It is a debugger that debugs Node.js, Chrome, Edge, WebView2, VS Code extensions, and more. You can safely un-install this extension and you will still be able to have the functionality you need.
Please file any issues you encounter in that repository.
Debug your JavaScript code running in Google Chrome from VS Code.
A VS Code extension to debug your JavaScript code in the Google Chrome browser, or other targets that support the Chrome DevTools Protocol.
Supported features
- Setting breakpoints, including in source files when source maps are enabled
- Stepping, including with the buttons on the Chrome page
- The Locals pane
- Debugging eval scripts, script tags, and scripts that are added dynamically
- Watches
- Console
Unsupported scenarios
- Debugging web workers
- Debugging Chrome extensions
- Any features that aren't script debugging
Getting Started
Using the debugger
When your launch config is set up, you can debug your project. Pick a launch config from the dropdown on the Debug pane in Code. Press the play button or F5 to start.
Configuration
The extension operates in two modes - it can launch an instance of Chrome navigated to your app, or it can attach to a running instance of Chrome. Both modes requires you to be serving your web application from local web server, which is started from either a VS Code task or from your command-line. Using the url parameter you simply tell VS Code which URL to either open or launch in Chrome.
Just like when using the Node debugger, you configure these modes with a .vscode/launch.json file in the root directory of your project. You can create this file manually, or Code will create one for you if you try to run your project, and it doesn't exist yet.
Launch
Two example launch.json configs with "request": "launch" . You must specify either file or url to launch Chrome against a local file or a url. If you use a url, set webRoot to the directory that files are served from. This can be either an absolute path or a path using $ (the folder open in Code). webRoot is used to resolve urls (like "http://localhost/app.js") to a file on disk (like /Users/me/project/app.js ), so be careful that it's set correctly.
If you want to use a different installation of Chrome, you can also set the runtimeExecutable field with a path to the Chrome app.
Attach
With "request": "attach" , you must launch Chrome with remote debugging enabled in order for the extension to attach to it. Here's how to do that:
Windows
- Right click the Chrome shortcut, and select properties
- In the "target" field, append --remote-debugging-port=9222
- Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222
macOS
- In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
Linux
- In a terminal, launch google-chrome --remote-debugging-port=9222
If you have another instance of Chrome running and don't want to restart it, you can run the new instance under a separate user profile with the --user-data-dir option. Example: --user-data-dir=/tmp/chrome-debug . This is the same as using the userDataDir option in a launch-type config.
Launch Chrome and navigate to your page.
An example launch.json file for an "attach" config.
Chrome user profile note ( Cannot connect to the target: connect ECONNREFUSED )
Normally, if Chrome is already running when you start debugging with a launch config, then the new instance won't start in remote debugging mode. So by default, the extension launches Chrome with a separate user profile in a temp folder. Use the userDataDir launch config field to override or disable this. If you are using the runtimeExecutable field, this isn't enabled by default, but you can forcibly enable it with "userDataDir": true .
If you are using an attach config, make sure you close other running instances of Chrome before launching a new one with --remote-debugging-port . Or, use a new profile with the --user-data-dir flag yourself.
For other troubleshooting tips for this error, see below.
Errors from chrome-error://chromewebdata
If you see errors with a location like chrome-error://chromewebdata/ in the error stack, these errors are not from the extension or from your app - they are usually a sign that Chrome was not able to load your app.
When you see these errors, first check whether Chrome was able to load your app. Does Chrome say "This site can't be reached" or something similar? You must start your own server to run your app. Double-check that your server is running, and that the url and port are configured correctly.
Other targets
Examples
See our wiki page for some configured example apps: Examples
Other optional launch config fields
- trace : When true, the adapter logs its own diagnostic info to a file. The file path will be printed in the Debug Console. This is often useful info to include when filing an issue on GitHub. If you set it to "verbose", it will also log to the console.
- runtimeExecutable : Workspace relative or absolute path to the runtime executable to be used. If not specified, Chrome will be used from the default install location.
- runtimeArgs : Optional arguments passed to the runtime executable.
- env : Optional dictionary of environment key/value pairs.
- cwd : Optional working directory for the runtime executable.
- userDataDir : Normally, if Chrome is already running when you start debugging with a launch config, then the new instance won't start in remote debugging mode. So by default, the extension launches Chrome with a separate user profile in a temp folder. Use this option to set a different path to use, or set to false to launch with your default user profile.
- url : On a 'launch' config, it will launch Chrome at this URL.
- urlFilter : On an 'attach' config, or a 'launch' config with no 'url' set, search for a page with this url and attach to it. It can also contain wildcards, for example, "localhost:*/app" will match either "http://localhost:123/app" or "http://localhost:456/app" , but not "https://stackoverflow.com" .
- targetTypes : On an 'attach' config, or a 'launch' config with no 'url' set, set a list of acceptable target types from the default ["page"] . For example, if you are attaching to an Electron app, you might want to set this to ["page", "webview"] . A value of null disables filtering by target type.
- sourceMaps : By default, the adapter will use sourcemaps and your original sources whenever possible. You can disable this by setting sourceMaps to false.
- pathMapping : This property takes a mapping of URL paths to local paths, to give you more flexibility in how URLs are resolved to local files. "webRoot": "$" is just shorthand for a pathMapping like < "/": "$" > .
- smartStep : Automatically steps over code that doesn't map to source files. Especially useful for debugging with async/await.
- disableNetworkCache : If false, the network cache will be NOT disabled. It is disabled by default.
- showAsyncStacks : If true, callstacks across async calls (like setTimeout , fetch , resolved Promises, etc) will be shown.
- breakOnLoad : Experimental. If true, the debug adapter will attempt to set breakpoints in scripts before they are loaded, so it can hit breakpoints at the beginnings of those scripts. Has a perf impact.
- breakOnLoadStrategy : The strategy used for breakOnLoad . Options are "Instrument" or "Regex". Instrument "[tells] Chrome to pause as each script is loaded, resolving sourcemaps and setting breakpoints" Regex "[s]ets breakpoints optimistically in files with the same name as the file in which the breakpoint is set."
Skip files / Blackboxing / Ignore files
You can use the skipFiles property to ignore/blackbox specific files while debugging. For example, if you set "skipFiles": ["jquery.js"] , then you will skip any file named 'jquery.js' when stepping through your code. You also won't break on exceptions thrown from 'jquery.js'. This works the same as "blackboxing scripts" in Chrome DevTools.
- The name of a file (like jquery.js )
- The name of a folder, under which to skip all scripts (like node_modules )
- A path glob, to skip all scripts that match (like node_modules/react/*.min.js )
Page refreshing
This debugger also enables you to refresh your target by simply hitting the restart button in the debugger UI. Additionally you can map the refresh action to your favorite keyboard shortcut by adding the following key mapping to Key Bindings:
Sourcemaps
The debugger uses sourcemaps to let you debug with your original sources, but sometimes the sourcemaps aren't generated properly and overrides are needed. In the config we support sourceMapPathOverrides , a mapping of source paths from the sourcemap, to the locations of these sources on disk. Useful when the sourcemap isn't accurate or can't be fixed in the build process.
The left hand side of the mapping is a pattern that can contain a wildcard, and will be tested against the sourceRoot + sources entry in the source map. If it matches, the source file will be resolved to the path on the right hand side, which should be an absolute path to the source file on disk.
A few mappings are applied by default, corresponding to some common default configs for Webpack and Meteor:
If you set sourceMapPathOverrides in your launch config, that will override these defaults. $ and $ can be used here. If you aren't sure what the left side should be, you can use the .scripts command (details below). You can also use the trace option to see the contents of the sourcemap, or look at the paths of the sources in Chrome DevTools, or open your .js.map file and check the values manually.
Ionic/gulp-sourcemaps note
Ionic and gulp-sourcemaps output a sourceRoot of "/source/" by default. If you can't fix this via your build config, I suggest this setting:
Usage with remote VS Code extensions
This extension can be used with the VS Code Remote Extensions to debug an app in a local Chrome window. Here's an example workflow using the Remote - SSH extension:
- Connect to the SSH remote where your project is located
- Launch the development server on the remote
- Run the "Forward Port From Active Host" command to forward the port the server is listening on. For example, if your development server is listening on port 3000, forward port 3000 to the local machine.
- Start your "chrome" launch config
- Chrome should start on the local machine, accessing your app via the forwarded port
- Debugging works as normally
There are a couple caveats to this workflow:
- Since the extension can't currently access the remote disk, sourcemaps can't be read from disk. If sourcemaps are inlined, they will still be used. If possible, they will be downloaded through your webserver.
- In a local window, when resolving your script locations with webRoot/pathMapping, the extension does some searching for the correct script. Again, since the extension can't check the remote disk, the extension can't do this searching, so your webRoot/pathMapping must be exactly accurate to resolve the script location.
If you have any other issues, please open an issue.
Troubleshooting
My breakpoints aren't hit. What's wrong?
If your breakpoints aren't hit, it's most likely a sourcemapping issue or because you are having breakpoints in immediately executed code. If you for example have a breakpoint in a render function that runs on page load, sometimes our debugger might not be attached to Chrome before the code has been executed. This means that you will have to refresh the page in Chrome after we have attached from VS Code to hit your breakpoint.
Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9222
This message means that the extension can't attach to Chrome, because Chrome wasn't launched in debug mode. Here are some things to try:
General things to try if you're having issues:
- Ensure webRoot is set correctly if needed
- Look at your sourcemap config carefully. A sourcemap has a path to the source files, and this extension uses that path to find the original source files on disk. Check the sourceRoot and sources properties in your sourcemap and make sure that they can be combined with the webRoot property in your launch config to build the correct path to the original source files.
- This extension ignores sources that are inlined in the sourcemap - you may have a setup that works in Chrome Dev Tools, but not this extension, because the paths are incorrect, but Chrome Dev Tools are reading the inlined source content.
- Check the console for warnings that this extension prints in some cases when it can't attach.
- Ensure the code in Chrome matches the code in Code. Chrome may cache an old version.
- If your breakpoints bind, but aren't hit, try refreshing the page. If you set a breakpoint in code that runs immediately when the page loads, you won't hit that breakpoint until you refresh the page.
- File a bug in this extension's GitHub repo, including the debug adapter log file. Create the log file by setting the "trace" field in your launch config and reproducing the issue. It will print the path to the log file at the top of the Debug Console. You can drag this file into an issue comment to upload it to GitHub.
- If you're using Webpack, we recommend using the "devtool": "source-map" option (in your webpack.config.js file) as the others produce lower-fidelity sourcemaps and you may have issues setting breakpoints. See the full list of devtool options for webpack for more information.
The .scripts command
This feature is extremely useful for understanding how the extension maps files in your workspace to files running in Chrome. You can enter .scripts in the Debug Console to see a listing of all scripts loaded in the runtime, their sourcemap information, and how they are mapped to files on disk. The format is like this:
If the paths of your source files show as not being resolved correctly here, you may have to change sourceMapPathOverrides or webRoot to help the debugger resolve them to real paths on disk.
If you are wondering what a script is, for example, that 'eval' script, you can also use .scripts to get its contents: .scripts eval://43 .
Visual Studio Code's debugging architecture allows extension authors to easily integrate existing debuggers into VS Code, while having a common user interface with all of them.
VS Code ships with one built-in debugger extension, the Node.js debugger extension, which is an excellent showcase for the many debugger features supported by VS Code:
This screenshot shows the following debugging features:
- Debug configuration management.
- Debug actions for starting/stopping and stepping.
- Source-, function-, conditional-, inline breakpoints, and log points.
- Stack traces, including multi-thread and multi-process support.
- Navigating through complex data structures in views and hovers.
- Variable values shown in hovers or inlined in the source.
- Managing watch expressions.
- Debug console for interactive evaluation with autocomplete.
This documentation will help you create a debugger extension which can make any debugger work with VS Code.
Debugging Architecture of VS Code
VS Code implements a generic (language-agnostic) debugger UI based on an abstract protocol that we've introduced to communicate with debugger backends. Because debuggers typically do not implement this protocol, some intermediary is needed to "adapt" the debugger to the protocol. This intermediary is typically a standalone process that communicates with the debugger.
We call this intermediary the Debug Adapter (or DA for short) and the abstract protocol that is used between the DA and VS Code is the Debug Adapter Protocol (DAP for short). Since the Debug Adapter Protocol is independent from VS Code, it has its own web site where you can find an introduction and overview, the detailed specification, and some lists with known implementations and supporting tools. The history of and motivation behind DAP is explained in this blog post.
Since debug adapters are independent from VS Code and can be used in other developments tools, they do not match VS Code's extensibility architecture which is based on extensions and contribution points.
For this reason VS Code provides a contribution point, debuggers , where a debug adapter can be contributed under a specific debug type (e.g. node for the Node.js debugger). VS Code launches the registered DA whenever the user starts a debug session of that type.
So in its most minimal form, a debugger extension is just a declarative contribution of a debug adapter implementation and the extension is basically a packaging container for the debug adapter without any additional code.
A more realistic debugger extension contributes many or all of the following declarative items to VS Code:
- List of languages supported by the debugger. VS Code enables the UI to set breakpoints for those languages. mention- JSON schema for the debug configuration attributes introduced by the debugger. VS Code uses this schema to verify the configuration in the launch.json editor and provides IntelliSense. Please note that the JSON schema constructs $ref and definition are not supported.
- Default debug configurations for the initial launch.json created by VS Code.
- Debug configuration snippets that a user can add to a launch.json file.
- Declaration of variables that can be used in debug configurations.
You can find more information in contributes.breakpoints and contributes.debuggers references.
In addition to the purely declarative contributions from above, the Debug Extension API enables this code-based functionality:
- Dynamically generated default debug configurations for the initial launch.json created by VS Code.
- Determine the debug adapter to use dynamically.
- Verify or modify debug configurations before they are passed to the debug adapter.
- Communicate with the debug adapter.
- Send messages to the debug console.
In the rest of this document we show how to develop a debugger extension.
The Mock Debug Extension
Since creating a debug adapter from scratch is a bit heavy for this tutorial, we will start with a simple DA which we have created as an educational "debug adapter starter kit". It is called Mock Debug because it does not talk to a real debugger, but mocks one. Mock Debug simulates a debugger and supports step, continue, breakpoints, exceptions, and variable access, but it is not connected to any real debugger.
Before delving into the development setup for mock-debug, let's first install a pre-built version from the VS Code Marketplace and play with it:
- Switch to the Extensions viewlet and type "mock" to search for the Mock Debug extension,
- "Install" and "Reload" the extension.
To try Mock Debug:
- Create a new empty folder mock test and open it in VS Code.
- Create a file readme.md and enter several lines of arbitrary text.
- Switch to the Run view and press the gear icon.
- VS Code will let you select an "environment" in order to create a default launch configuration. Pick "Mock Debug".
- Press the green Start button and then Enter to confirm the suggested file readme.md .
A debug session starts and you can "step" through the readme file, set and hit breakpoints, and run into exceptions (if the word exception appears in a line).
Before using Mock Debug as a starting point for your own development, we recommend to uninstall the pre-built version first:
- Switch to the Extensions viewlet and click on the gear icon of the Mock Debug extension.
- Run the "Uninstall" action and then "Reload" the window.
Development Setup for Mock Debug
Now let's get the source for Mock Debug and start development on it within VS Code:
Open the project folder vscode-mock-debug in VS Code.
What's in the package?
- package.json is the manifest for the mock-debug extension:
- It lists the contributions of the mock-debug extension.
- The compile and watch scripts are used to transpile the TypeScript source into the out folder and watch for subsequent source modifications.
- The dependencies vscode-debugprotocol , vscode-debugadapter , and vscode-debugadapter-testsupport are NPM modules that simplify the development of node-based debug adapters.
Now build and launch the Mock Debug extension by selecting the Extension launch configuration and hitting F5 . Initially, this will do a full transpile of the TypeScript sources into the out folder. After the full build, a watcher task is started that transpiles any changes you make.
After transpiling the source, a new VS Code window labelled "[Extension Development Host]" appears with the Mock Debug extension now running in debug mode. From that window open your mock test project with the readme.md file, start a debug session with 'F5', and then step through it:
Since you are running the extension in debug mode, you could now set and hit breakpoints in src/extension.ts but as I've mentioned above, there is not much interesting code executing in the extension. The interesting code runs in the debug adapter which is a separate process.
In order to debug the debug adapter itself, we have to run it in debug mode. This is most easily achieved by running the debug adapter in server mode and configure VS Code to connect to it. In your VS Code vscode-mock-debug project select the launch configuration Server from the dropdown menu and press the green start button.
Since we already had an active debug session for the extension the VS Code debugger UI now enters multi session mode which is indicated by seeing the names of the two debug sessions Extension and Server showing up in the CALL STACK view:
Now we are able to debug both the extension and the DA simultaneously. A faster way to arrive here is by using the Extension + Server launch configuration which launches both sessions automatically.
An alternative, even simpler approach for debugging the extension and the DA can be found below.
Set a breakpoint at the beginning of method launchRequest(. ) in file src/mockDebug.ts and as a last step configure the mock debugger to connect to the DA server by adding a debugServer attribute for port 4711 to your mock test launch config:
If you now launch this debug configuration, VS Code does not start the mock debug adapter as a separate process, but directly connects to local port 4711 of the already running server, and you should hit the breakpoint in launchRequest .
With this setup, you can now easily edit, transpile, and debug Mock Debug.
But now the real work begins: you will have to replace the mock implementation of the debug adapter in src/mockDebug.ts and src/mockRuntime.ts by some code that talks to a "real" debugger or runtime. This involves understanding and implementing the Debug Adapter Protocol. More details about this can be found here.
Anatomy of the package.json of a Debugger Extension
Besides providing a debugger-specific implementation of the debug adapter a debugger extension needs a package.json that contributes to the various debug-related contributions points.
So let's have a closer look at the package.json of Mock Debug.
Like every VS Code extension, the package.json declares the fundamental properties name, publisher, and version of the extension. Use the categories field to make the extension easier to find in the VS Code Extension Marketplace.
Now take a look at the contributes section which contains the contributions specific to debug extensions.
First, we use the breakpoints contribution point to list the languages for which setting breakpoints will be enabled. Without this, it would not be possible to set breakpoints in Markdown files.
Next is the debuggers section. Here, one debugger is introduced under a debug type mock . The user can reference this type in launch configurations. The optional attribute label can be used to give the debug type a nice name when showing it in the UI.
Since the debug extension uses a debug adapter, a relative path to its code is given as the program attribute. In order to make the extension self-contained the application must live inside the extension folder. By convention, we keep this applications inside a folder named out or bin , but you are free to use a different name.
Since VS Code runs on different platforms, we have to make sure that the DA program supports the different platforms as well. For this we have the following options:
If the program is implemented in a platform independent way, e.g. as program that runs on a runtime that is available on all supported platforms, you can specify this runtime via the runtime attribute. As of today, VS Code supports node and mono runtimes. Our Mock debug adapter from above uses this approach.
If your DA implementation needs different executables on different platforms, the program attribute can be qualified for specific platforms like this:
A combination of both approaches is possible too. The following example is from the Mono DA which is implemented as a mono application that needs a runtime on macOS and Linux but not on Windows:
configurationAttributes declares the schema for the launch.json attributes that are available for this debugger. This schema is used for validating the launch.json and supporting IntelliSense and hover help when editing the launch configuration.
The initialConfigurations define the initial content of the default launch.json for this debugger. This information is used when a project does not have a launch.json and a user starts a debug session or clicks on the gear icon in the Run view. In this case VS Code lets the user pick a debug environment and then creates the corresponding launch.json :
Instead of defining the initial content of the launch.json statically in the package.json , it is possible to compute the initial configurations dynamically by implementing a DebugConfigurationProvider (for details see the section Using a DebugConfigurationProvider below).
configurationSnippets define launch configuration snippets that get surfaced in IntelliSense when editing the launch.json . As a convention, prefix the label attribute of a snippet by the debug environment name so that it can be clearly identified when presented in a list of many snippet proposals.
The variables contribution binds "variables" to "commands". These variables can be used in the launch configuration using the $ syntax and the variables are substituted by the value returned from the bound command when a debug session is started.
The implementation of a command lives in the extension and it can range from a simple expression with no UI, to sophisticated functionality based on the UI features available in the extension API. Mock Debug binds a variable AskForProgramName to the command extension.mock-debug.getProgramName . The implementation of this command in src/extension.ts uses the showInputBox to let the user enter a program name:
The variable can now be used in any string typed value of a launch configuration as $ .
Using a DebugConfigurationProvider
If the static nature of debug contributions in the package.json is not sufficient, a DebugConfigurationProvider can be used to dynamically control the following aspects of a debug extension:
- The initial debug configurations for a newly created launch.json can be generated dynamically, e.g. based on some contextual information available in the workspace.
- A launch configuration can be resolved (or modified) before it is used to start a new debug session. This allows for filling in default values based on information available in the workspace. Two resolve methods exist: resolveDebugConfiguration is called before variables are substituted in the launch configuration, resolveDebugConfigurationWithSubstitutedVariables is called after all variables have been substituted. The former must be used if the validation logic inserts additional variables into the debug configuration. The latter must be used if the validation logic needs access to the final values of all debug configuration attributes.
The MockConfigurationProvider in src/extension.ts implements resolveDebugConfiguration to detect the case where a debug session is started when no launch.json exists, but a Markdown file is open in the active editor. This is a typical scenario where the user has a file open in the editor and just wants to debug it without creating a launch.json.
A debug configuration provider is registered for a specific debug type via vscode.debug.registerDebugConfigurationProvider , typically in the extension's activate function. To ensure that the DebugConfigurationProvider is registered early enough, the extension must be activated as soon as the debug functionality is used. This can be easily achieved by configuring extension activation for the onDebug event in the package.json :
This catch-all onDebug is triggered as soon as any debug functionality is used. This works fine as long as the extension has cheap startup costs (i.e. does not spend a lot of time in its startup sequence). If a debug extension has an expensive startup (for instance because of starting a language server), the onDebug activation event could negatively affect other debug extensions, because it is triggered rather early and does not take a specific debug type into account.
A better approach for expensive debug extensions is to use more fine-grained activation events:
- onDebugInitialConfigurations is fired just before the provideDebugConfigurations method of the DebugConfigurationProvider is called.
- onDebugResolve:type is fired just before the resolveDebugConfiguration or resolveDebugConfigurationWithSubstitutedVariables methods of the DebugConfigurationProvider for the specified type is called.
Rule of thumb: If activation of a debug extensions is cheap, use onDebug . If it is expensive, use onDebugInitialConfigurations and/or onDebugResolve depending on whether the DebugConfigurationProvider implements the corresponding methods provideDebugConfigurations and/or resolveDebugConfiguration .
Publishing your debugger extension
Once you have created your debugger extension you can publish it to the Marketplace:
- Update the attributes in the package.json to reflect the naming and purpose of your debugger extension.
- Upload to the Marketplace as described in Publishing Extension.
Alternative approach to develop a debugger extension
As we have seen, developing a debugger extension typically involves debugging both the extension and the debug adapter in two parallel sessions. As explained above VS Code supports this nicely but development could be easier if both the extension and the debug adapter would be one program that could be debugged in one debug session.
This approach is in fact easily doable as long as your debug adapter is implemented in TypeScript/JavaScript. The basic idea is to run the debug adapter directly inside the extension and to make VS Code to connect to it instead of launching a new external debug adapter per session.
For this VS Code provides extension API to control how a debug adapter is created and run. A DebugAdapterDescriptorFactory has a method createDebugAdapterDescriptor that is called by VS Code when a debug session starts and a debug adapter is needed. This method must return a descriptor object ( DebugAdapterDescriptor ) that describes how the debug adapter is run.
Today VS Code supports three different ways for running a debug adapter and consequently offers three different descriptor types:
Mock Debug shows examples for the three types of DebugAdapterDescriptorFactories and how they are registered for the 'mock' debug type. The run mode to use can be selected by setting the global variable runMode to one of the possible values external , server , or inline .
For development, the inline and server modes are particularly useful because they allow for debugging extension and debug adapter within a single process.
Перевод статьи «How to set up the debugger for Chrome extension in Visual Studio Code».
Отладка веб-приложений с помощью Visual Studio Code повышает эффективность вашей работы. Она помогает сэкономить много времени и поддерживать чистоту кода. А все потому, что вам не приходится писать целую кучу console.log и вы можете просматривать выполнение вашего кода построчно. Но раз вы уже здесь, вы, вероятно, и так знаете о преимуществах отладки веб-приложений. Итак, начнем…
Разбираемся в настройках
Для начала вам нужно установить расширение Debugger for Chrome. (Для этого откройте VS Code, нажмите Ctrl+P, вставьте в открывшейся строке команду ext install msjsdiag.debugger-for-chrome и нажмите enter). После установки отладчик можно начинать использовать практически сразу.
Но вы можете настраивать поведение отладчика для каждого своего проекта (поэтому для дальнейших действий следует сразу открыть папку нужного проекта).
Далее вам нужно создать файл запуска для Visual Studio Code Debugger. Этот файл будет содержать различные настройки отладчика для выбранного проекта.
Для создания файла запуска нужно перейти в раздел отладки в панели действий (Activity Bar ) и кликнуть на значок шестеренки.
Значок шестеренки
Вам будет предложен список вариантов, из которых нужно выбрать «Chrome».
Вот так.
После этого в папке вашего проекта появится директория .vscode с файлом launch.json. Этот файл также откроется в вашем VS Code; в нем мы и будем указывать настройки конфигурации.
Конфигурация
Есть два вида конфигурации отладчика: launch и attach. Устанавливаются они в опции request. Выбирать нужный вид можно для каждого отдельного объекта конфигурации.
Launch
Конфигурация Launch предполагает запуск отдельного экземпляра Chrome, в котором выполняется указанный файл или URL.
Если вы указываете URL, вам нужно указать директорию, файлы которой обслуживаются, в опции webRoot. Это можно сделать путем указания абсолютного пути или с использованием преобразователя $ (он указывает на папку, открытую в вашем рабочем пространстве Visual Studio Code).
Примечание: будьте осторожны при указании webRoot, поскольку эта опция используется, чтобы резолвить URL к файлам на вашем компьютере.
В примере вы можете видеть два варианта конфигурации launch: один предполагает запуск локального сервера, а другой – отдельного файла.
[javascript]
"version": "0.2.0",
"configurations": [
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "$"
>,
"type": "chrome",
"request": "launch",
"name": "Open a specific file",
"file": "$/index.html"
>
]
>[/javascript]Если у вас уже есть запущенный экземпляр Chrome, то экземпляр, запускаемый отладчиком, будет использовать временную сессию. То есть, у вас не будет ваших расширений или открытых вкладок. Если вы хотите, чтобы отладчик запустил экземпляр Chrome с вашими пользовательскими настройками и расширениями, вам сначала нужно закрыть все открытые экземпляры Chrome.
Примечание: когда вы остановите отладчик, окно Chrome закроется.
Attach
Лично я предпочитаю этот вариант. Эта конфигурация присоединяет отладчик к запущенному экземпляру Chrome. Но чтобы этот вариант работал, вам нужно запустить Chrome с включенной опцией удаленной отладки. Как это сделать, зависит от вашей операционной системы.
Windows
Есть два способа запустить Chrome с удаленной отладкой в Windows. Самый простой – кликнуть правой кнопкой мыши по ярлыку Google Chrome. Затем нужно выбрать нужную опцию в свойствах и добавить следующую команду в поле target.
Примечание: таким образом Chrome с возможностью удаленной отладки будет запускаться каждый раз, как вы кликнете по ярлыку.
Другой способ – открыть командную строку и выполнить в ней следующую команду (заменив при этом на настоящее местоположение установки вашего Chrome):
macOS
Откройте терминал и выполните следующую команду:
Linux
Откройте терминал и выполните следующую команду:
Указанные команды (во всех трех вариантах) открывают Chrome с дополнительной опцией, которая указывает порт для удаленной отладки – 9222. Узнать больше по этой теме можно здесь.
Примечание: если у вас запущены другие экземпляры Chrome с удаленной отладкой, позаботьтесь о том чтобы закрыть их, прежде чем запускать новый экземпляр.
Вот пример конфигурации attach:
[javascript]
"version": "0.2.0",
"configurations": [
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9222,
"url": "http://localhost:3000",
"webRoot": "$/src"
>
]
>
[/javascript]Примечание: если вы не установите опцию «url», вам будет предложен список из ваших открытых вкладок.
Это расширение имеет множество очень полезных опций, которые вы можете использовать для подгонки конфигурации отладчика для вашего проекта. Документацию некоторых из них можно почитать здесь.
Заключение
Поздравляем! Вы научились устанавливать и настраивать отладчик для Chrome в Visual Studio Code. Также вы научились запускать Google Chrome с включенной возможностью удаленной отладки. Теперь пора исследовать это расширение и углубить свои знания. Я настоятельно советую изучить репозиторий этого расширения.
Подпишись на наш канал с тестами по HTML/CSS/JS в Telegram!
Сайт proglib.io опубликовал свой перевод англоязычной статьи с подборкой расширений для редактора VSCode. Надеемся, фронтендерам будет интересно.
Десятка расширений редактора Visual Studio Code для фронтенд-разработчика: линтинг, отладка, журналирование, работа с Git и многое другое.
1. Turbo Console Log
2. Quokka.js
Расширение Quokka позволяет тестировать JavaScript-код, не переходя в консоль браузера. Ещё Quokka помогает в прототипировании и работе с файлами. Есть встроенные отчеты и форматирование выходных данных.
3. Prettier
Популярное расширение Prettier помогает форматировать JavaScript-код, делая текст программы более читаемым, а стиль кода – согласованным. Можно форматировать не только JavaScript, но и TypeScript, JSON, GraphQL и другие языки программирования и разметки, учитывая особенности популярных библиотек и фреймворков.
4. Live Share Extension Pack
Live Server – пакет расширений для совместного редактирования и отладки в режиме реального времени. Есть даже голосовой и текстовый чаты, удаленный обзор кода и Live Reload для перезагрузки страницы при сохранении проекта. Всё устанавливается в один клик.
5. GitLens
Расширение GitLens обрабатывает и визуализирует в редакторе информацию Git. В том числе логи коммитов и файловую историю. С помощью аннотаций git blame и code lens можно визуализировать историю работы над проектом.
6. Polacode
Расширение Polacode позволяет удобно делать красивые скриншоты фрагментов кода.
7. vscode-icons
Расширение VScode-icons добавляет иконки файлов в Visual Studio Code. Найти нужный файл будет ещё проще.
8. open in browser
Используя расширение Open in browser, можно открывать в браузере любые типы файлов, а не только HTML-документы.
9. ESLint
ESLint – инструмент, который приводит разношерстный JavaScript код проекта к единому стилю. Во многом похож на JSLint и JSHint, но есть и отличия:
- для синтаксического анализа JS используется Espree;
- для оценки шаблонов в коде применяется AST;
- продукт полностью встраиваемый, каждое правило является плагином, которое можно добавить их в рантайме.
10. Markdown Preview Enhanced
Расширение Markdown Preview Enhanced предоставляет множество полезных функций: автосинхронизация скролла, поддержка языка диаграмм PlantUML, pandoc, экспорт PDF, создание презентаций и т. д. Отлично подойдет тем, кто знаком с Markdown Preview Plus или RStudio Markdown.
Заключение
Мы рассмотрели десять полезных расширений VS Code, призванных улучшить, ускорить и облегчить процесс разработки. Обязательно попробуйте их в деле или поделитесь теми, что используете сами.
Читайте также: