Let's get debugging
Updated: Mar 13, 2019
You make a change to the code and it does not work as you expect. What now? Getting the debugger working will certainly help with that. Here's how I set up the debugger with Visual Studio Code and Chrome.
I believe it is possible to use Edge and other browsers for debugging but I won't be covering how to do that in this post.
Visual Studio Code extension
In Visual Studio Code, search for the Debugger for Chrome extension and install it. Restart Visual Studio Code if necessary.
You should now see a debugger tab:
A local debugging session can be started by pressing F5 or clicking on the green Run arrow, however, as a local session the web part cannot read information from the SharePoint site. I want to debug my web part when it has access to the SharePoint lists and libraries.
Launch.json config file
Look for the .vscode folder where you created your project. This should contain a launch.json file. If not, one can be created by clicking on the settings cog in the debugger section.
Open and edit the file. Look for the "url" key in the "Hosted workbench" section.
* Install Chrome Debugger Extension for Visual Studio Code to debug your components with the
* Chrome browser: https://aka.ms/spfx-debugger-extensions
... snip ...
"name": "Hosted workbench",
Change the "url" value to point to your SharePoint site and ensure the address retains the following at the end: /_layouts/15/workbench.aspx. Note: change the 'Your-Site-Here' and 'sites/TestSite' as needed.
Visual Studio Code now has the information it needs to launch your SharePoint site's workbench to allow debugging and your web part will have access to the lists and libraries.
Starting a hosted debugging session
On the Debugger tab in Visual Studio Code, change to the Hosted workbench.
Then press the F5 key to start the debugger. With the Hosted workbench configuration, an incognito Chrome window will be opened and you will be asked to sign in to your SharePoint site. Enter your credentials and you will arrive at the workbench on your SharePoint site. Add the web part to the workbench. Remember, if you don't see it you have likely forgotten to execute gulp serve!
With the web part added to the workbench any breakpoints you set will show as a solid red dot and should halt the program when hit. The usual Visual Studio debugger keys (F5, F10, F11 etc) all work and there is also a debug toolbar with the buttons to step in, step over and so on, should you prefer.
To finish debugging, click the stop button or close the Chrome incognito browser window.
There is a small gotcha, and I'm not sure how to handle it yet. Sometimes, especially when I write some dodgy React code the debugger can get caught in the React JS library and it won't budge from there. Closing the Chrome browser window will usually clear it but I wonder if there is a better way to recover from this? Please let me know in the comments.