Debug react app vscode

Debug react app vscode DEFAULT

Debugging a Create React App with VS Code

In this post (and the above 4 minute embedded video) we’ll look at how to configure Visual Studio Code to debug React Components and Jest Unit Tests inside a web application that was created by .

This is the second post in a series about . You can start the series with Getting Started with Create React App.

Sample Web Application

Screenshot of Terminal & Empty Browser

On the left, we have a simple web application that was previously created with .

We can easily kick up a development web server by typing in the terminal. will create a new browser tab to the correct URL and port (e.g. ).

Screenshot of Terminal & Web App

However, our React web application has a bug. If I click on the joke, the answer does not display.

Debugging React Components

By looking at the following code, it may not be obvious what is causing the bug. Wouldn’t it be great if we could debug this code right inside of Visual Studio Code? Well, we can!

Screenshot of Code
  1. Chrome Debugger

Before we can start debugging, you need to make sure we have the extension installed and reloaded.

Screenshot of Debugger for Chrome Extension
  1. Making Breakpoints

Now, we can start making some breakpoints right were we would like to investigate your code.

Screenshot of Breakpoints
  1. Chrome Launch Configuration

Next, from the debug panel you need to configure the launch script for chrome. If you don’t have any existing scripts, then you can just select one like “chrome” for example from the gear icon. It doesn’t really matter, as we are going to clear out the contents and replace it anyway.

Let’s go to the official documentation and grab the launch configuration to debug your web application. Just copy the whole snippet, and paste it in your file.

Screenshot of Launch Configuration

NOTE: The following snippet may change as evolves. Please refer to the official documentation for the latest configuration snippet.

  1. Launch Chrome Debugger

And now, we are ready to debug our web app. Go up to the green arrow and make sure “Chrome” is selected in the dropdown, then click the green arrow.

This will kick up yet another browser instance, one that is connected to VS Code’s debugger. At this point, you’ll probably need to refresh your browser to initiate your breakpoint.

Soon we'll reach our first breakpoint inside of VS Code!

Screenshot of Live Debugger

From here, you have access to look around at your local variables in the left panel. There are options to add watches, browse the call stack, etc… There is also a handy interactive Debug Console. For example, you can change the value of isFlipped to to simulate that we actually clicked the joke.

You can step over the breakpoint and hover over the variable to inspect it’s value at this point in time. For our bug, the problem is that the className should have two dashes and not just one (as its using the SUIT CSS naming convention to indicate it’s a modifier). Thankfully, that’s easy to fix by adding an extra dash.

Now, we can stop the debugger and retry our web app and sure enough, it works just fine!

Screenshot of Live Debugger

Debugging Unit Tests

Now that we have our web application code all fixed up, let’s move to debugging our Jest unit tests.

  1. Debug CRA Tests Launch Configuration

Here we have some code testing the behavior of our React component.

Screenshot of Failing Tests

However, if we come to the terminal and run our Jest tests you’ll notice that one of them is failing at the moment. Let’s go inside and add a breakpoint to debug our code.

Unfortunately, our previous launch script will not help us in this situation, but we can also go out to the official documentation to find the snippet we need. From the documentation you can copy the configuration section, add it to the array that you already have in your , and save the file.

Screenshot of Debugging Tests

NOTE: The following snippet may change as evolves. Please refer to the official documentation for the latest configuration snippet.

  1. Launch Debug CRA Tests Debugger

Now, switch the option in the dropdown to “Debug CRA Test” and click the green arrow. This will kick off Jest and then VS Code will stop at our breakpoint.

Screenshot of Debugging Tests

Like before, we could look at the local variables panel, but we will come down to the debug console and inspect the DOM element’s text context. Ohhhh, hello has a instead of an in it. Let’s fix that, save, and rerun our tests. Yup, that was it. Our tests are all green now.

Screenshot of Debugging Tests

Conclusion

Thanks for reading this second post in the series. The above video is the first in a series, so stay tuned.

Share on TwitterDiscuss on TwitterFollow @elijahmanor

Tweet about this post and have it show up here!

Sours: https://elijahmanor.com/blog/cra-debug-vscode

Live edit and debug your React apps directly from VS Code — without leaving the editor 🔥 🎉🎈

In our most recent release of our Chrome debugger for VS Code, we have landed a bunch of improvements to our sourcemapping-engine, which enables us to support live-editing and debugging out of the box with create-react-app.

Demo of React app being live edited and debugged from VS Code

This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.

You can now write code, set a breakpoints, make a changes to the code, and debug your newly modified code — all from your editor 🔥 🎉🎈

How to get started in 6 steps

  1. Download the latest release of VS Code and install our Chrome debugger
  2. Create your React app using create-react-app
  3. Use the following config for your file to configure the VS Code debugger and put it inside  in your root folder.
  4. Start your React app by running in your favorite terminal
  5. Start debugging in VS Code by pressing or by clicking the green debug icon

Happy debugging! 🎉🎈

Details

Our Chrome debugger now supports Webpack’s Hot Module Replacement mechanism, which pushes module changes to the browser by running a local file watcher.

Our debugger is now able to pickup these changes and re-applies the newly generated HMR sourcemap to the loaded source files on the fly. This enables the live editing and debugging experiences, without adding a need for more file watches or background tools.

/k

Sours: https://kenneth.io/post/live-edit-and-debug-your-react-apps-directly-from-vs-code-without-leaving-the-editor
  1. Uva course schedule
  2. Oregon crawfish season
  3. New adult movie releases

How do you debug your JavaScript? I’m pretty sure that most of you would answer anything like , or – if it’s a React app – . Yep, me too 🙂

Usually, when there is something off in one of my apps, I follow a certain strategy:

console.log debugging like a pro

  1. navigate to the part of the code where I suspect the bug
  2. throw in a bunch of statements
  3. reload the app
  4. switch to the browser
  5. navigate to that part of the app where the bug appears
  6. perform the actions to reproduce the bug
  7. check the browser console

… just to see that I didn’t the right variables, missed a place to log, etc. you name it.

So again, I switch back to the editor and start all over again at 1. *ugh*

Sometimes, debugging involves a lot of switching between browser and editor, navigating, reproducing and restarting. Possibly a lot of cursing too. And we can reduce a bit of the switching by using the debugger that is built into Visual Studio Code.

Why not just use the debugger of your browser,  you ask?

What about the browser’s dev tools?

We can indeed just use what’s already there. We can add breakpoints and inspect the code in your chrome dev tools too. But we still have to go back to VSCode to edit our code before again switching to the browser to reload the app and check if it worked.

If we’re writing your code in VSCode anyways, so why not leverage it’s debugging feature?

The VSCode Debugger

Using the built in debugger can spare you a lot of switching between windows, because you can just step through your code while performing changes – all in the same place!

Configure VSCode

So let’s have a look at how to configure VSCode to debug our React app.

Note: The following configuration will only work for client-side apps. For server-side rendered apps we would need a different configuration.

Prerequisites

First of all, install the extension “Debugger for Chrome”. It allows VSCode to access to our browser’s dev tools to span the gap between browser and editor.

Add Debug Configuration

Next, switch to the Debug tab, and on the top of the sidebar, click the configurations dropdown to select “Add Configuration”

You should now see a dropdown to select an Environment. Click “Chrome”

At this point, a launch.json will be generated. This is the configuration of the VSCode debugger for your project.

Adapt launch.json to your Project

In launch.json, edit two values:

  1. The URL to the url and port of your app. If you created your app with , it would be http://localhost:3000
  2. Change to ${workspaceFolder}/src or – if you didn’t use CRA – to a directory where your is located.

Starting your Debug Session

If it’s not already started, spin up your development server with and begin your debug session by clicking the green arrow in the debug tab. Just be sure, that your previously created debug configuration is selected in the dropdown besides it.

As soon as the debugging session starts, a new Chrome window will appear and the status bar of your VSCode will turn orange.

Congratulations! Now you can set your breakpoints, watch your locales and edit code while stepping through it.

I have uploaded a working launch.jsonhere. Just download it into your project directory to .vscode/launch.json

Photo by Paulo Ziemer on Unsplash

Share this article with your friends:

Related

Sours: https://www.andreasreiterer.at/set-up-vscode-debugger-react/
React Native Tutorial #21 (2021) - Debugging in VS Code

Using React in Visual Studio Code

React is a popular JavaScript library developed by Facebook for building web application user interfaces. The Visual Studio Code editor supports React.js IntelliSense and code navigation out of the box.

Welcome to React

Welcome to React

We'll be using the generator for this tutorial. To use the generator as well as run the React application server, you'll need Node.js JavaScript runtime and npm (Node.js package manager) installed. npm is included with Node.js which you can download and install from Node.js downloads.

Tip: To test that you have Node.js and npm correctly installed on your machine, you can type and in a terminal or command prompt.

You can now create a new React application by typing:

where is the name of the folder for your application. This may take a few minutes to create the React application and install its dependencies.

Note: If you've previously installed globally via , we recommend you uninstall the package using to ensure that npx always uses the latest version.

Let's quickly run our React application by navigating to the new folder and typing to start the web server and open the application in a browser:

You should see the React logo and a link to "Learn React" on http://localhost:3000 in your browser. We'll leave the web server running while we look at the application with VS Code.

To open your React application in VS Code, open another terminal or command prompt window, navigate to the folder and type :

Markdown preview

In the File Explorer, one file you'll see is the application Markdown file. This has lots of great information about the application and React in general. A nice way to review the README is by using the VS Code Markdown Preview. You can open the preview in either the current editor group (Markdown: Open Preview⇧⌘V (Windows, Linux Ctrl+Shift+V)) or in a new editor group to the side (Markdown: Open Preview to the Side⌘K V (Windows, Linux Ctrl+K V)). You'll get nice formatting, hyperlink navigation to headers, and syntax highlighting in code blocks.

README Markdown Preview

Syntax highlighting and bracket matching

Now expand the folder and select the file. You'll notice that VS Code has syntax highlighting for the various source code elements and, if you put the cursor on a parenthesis, the matching bracket is also selected.

React bracket matching

IntelliSense

As you start typing in , you'll see smart suggestions or completions.

React IntelliSense suggestions

After you select a suggestion and type , you see the types and methods on the object through IntelliSense.

React IntelliSense

VS Code uses the TypeScript language service for its JavaScript code intelligence and it has a feature called Automatic Type Acquisition (ATA). ATA pulls down the npm Type Declaration files () for the npm modules referenced in the .

If you select a method, you'll also get parameter help:

React parameter help

Go to Definition, Peek definition

Through the TypeScript language service, VS Code can also provide type definition information in the editor through Go to Definition (F12) or Peek Definition (⌥F12 (Windows Alt+F12, Linux Ctrl+Shift+F10)). Put the cursor over the , right click and select Peek Definition. A Peek window will open showing the definition from .

React Peek definition

Press Escape to close the Peek window.

Hello World!

Let's update the sample application to "Hello World!". Create a new H1 header with "Hello, world!" and replace the tag in with .

Once you save the file, the running instance of the server will update the web page and you'll see "Hello World!" when you refresh your browser.

Tip: VS Code supports Auto Save, which by default saves your files after a delay. Check the Auto Save option in the File menu to turn on Auto Save or directly configure the user setting.

Hello, world

Debugging React

To debug the client side React code, we'll use the built-in JavaScript debugger.

Note: This tutorial assumes you have the Edge browser installed. If you want to debug using Chrome, replace the launch with . There is also a debugger for the Firefox browser.

Set a breakpoint

To set a breakpoint in , click on the gutter to the left of the line numbers. This will set a breakpoint which will be visible as a red circle.

Set a breakpoint

Configure the debugger

We need to initially configure the debugger. To do so, go to the Run view (⇧⌘D (Windows, Linux Ctrl+Shift+D)) and click on the gear button or Create a launch.json link to create a debugger configuration file. Choose Edge: launch from the Select Environment dropdown list. This will create a file in a new folder in your project which includes a configuration to launch the website.

We need to make one change for our example: change the port of the from to . Your should look like this:

Ensure that your development server is running (). Then press F5 or the green arrow to launch the debugger and open a new browser instance. The source code where the breakpoint is set runs on startup before the debugger was attached, so we won't hit the breakpoint until we refresh the web page. Refresh the page and you should hit your breakpoint.

Debugger hitting breakpoint

You can step through your source code (F10), inspect variables such as , and see the call stack of the client side React application.

Debug element variable

For more information about the debugger and its available options, check out our documentation on browser debugging.

Live editing and debugging

If you are using webpack together with your React app, you can have a more efficient workflow by taking advantage of webpack's HMR mechanism which enables you to have live editing and debugging directly from VS Code. You can learn more in this Live edit and debug your React apps directly from VS Code blog post and the webpack Hot Module Replacement documentation.

Linting

Linters analyze your source code and can warn you about potential problems before you run your application. The JavaScript language services included with VS Code has syntax error checking support by default, which you can see in action in the Problems panel (View > Problems⇧⌘M (Windows, Linux Ctrl+Shift+M)).

Try making a small error in your React source code and you'll see a red squiggle and an error in the Problems panel.

JavaScript error

Linters can provide more sophisticated analysis, enforcing coding conventions and detecting anti-patterns. A popular JavaScript linter is ESLint. ESLint, when combined with the ESLint VS Code extension, provides a great in-product linting experience.

First, install the ESLint command-line tool:

Then install the ESLint extension by going to the Extensions view and typing 'eslint'.

ESLint extension

Once the ESLint extension is installed and VS Code reloaded, you'll want to create an ESLint configuration file, . You can create one using the extension's ESLint: Create ESLint configuration command from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

Find the configuration command

The command will prompt you to answer a series of questions in the Terminal panel. Take the defaults, and it will create a file in your project root that looks something like this:

ESLint will now analyze open files and shows a warning in about 'App' being defined but never used.

App is unused

You can modify the ESLint rules in the file.

Let's add an error rule for extra semi-colons:

Now when you mistakenly have multiple semicolons on a line, you'll see an error (red squiggle) in the editor and error entry in the Problems panel.

Extra semicolon error

Popular Starter Kits

In this tutorial, we used the generator to create a simple React application. There are lots of great samples and starter kits available to help build your first React application.

VS Code React Sample

This is a sample React application, which creates a simple TODO application and includes the source code for a Node.js Express server. It also shows how to use the Babel ES6 transpiler and then use webpack to bundle the site assets.

TypeScript React

If you're curious about TypeScript and React, you can also create a TypeScript version of the application by specifying that you want to use the TypeScript template:

See the details at Adding TypeScript on the Create React App site.

Angular

Angular is another popular web framework. If you'd like to see an example of Angular working with VS Code, check out the Debugging with Angular CLI recipe. It will walk you through creating an Angular application and configuring the file for the JavaScript debugger.

Common questions

Can I get IntelliSense within declarative JSX?

Yes. For example, if you open the project's file, you can see IntelliSense within the React JSX in the method.

JSX IntelliSense

10/7/2021

Sours: https://code.visualstudio.com/docs/nodejs/reactjs-tutorial

App vscode react debug

Debugging Create React App Applications in Visual Studio Code

In this post, we are going to create an Create React App application, then add configuration to debug it in Visual Studio Code.

Check out Learn Visual Studio Code to learn everything you need to know about about the hottest editor in Web Development for only $10!

TLDR - For an Create React App application, install the Debugger for Chrome extension, create a debug configuration in VS Code, and then run in debug mode.

Learn VS Code

Learn VS Code

If you're interested in learning more about VS Code, you definitely want to check out the upcoming Learn VS Code course.

Creating a Starter Project

To be able to test an Create React App application, you need an Create React App application :) I'll provide the basic steps, but for more reference on how to get started look at the Create React App page.

First, you'll need to install the Create React App.

Get Started w/ JavaScriptfor free!

After that finishes, you'll need to actually generate your new application. This will take a bit as it needs to install LOTS of NPM packages.

Open the project in VS Code and you should see the following.

Create React App Project in VS Code

Now, that you've got your new fancy React app, go ahead and run it to make sure everything looks right.

Should look like this.

Create React App Project Running

Creating Debug Configuration

Assuming you've made it this far, we are ready to start debugging! Before we do, however, it's worth understanding how configuring debugging in VS Code works. Basically debug configurations are saved in a launch.json file which is stored inside of a .vscode folder. This .vscode folder is used to store different configurations for Code including our required debugging stuff.

Before you create your debug configuration, you need to install the Debugger for Chrome extension. Find and install this extension from the extension tab in VS Code. After installing, reload VS Code.

Debugger for Chrome

Now, to create a debug configuration, you can open the debug panel (the bug looking button on the left panel). At the top of the debug panel, you should see a dropdown that says "No Configurations".

Create Debug Configurations

To the right of that dropdown, there is a gear icon. Click this button to have VS Code automatically generate that folder and file mentioned above.

Then choose Chrome.

Choose Chrome Debug Configuration

You should get the following configuration created for you.

Create React App Debug Configuration

The only thing we need to do is update the port from 8080 to 3000.

Updated Create React App Debug Configuration

Let's Debug

Now we're ready! Go ahead and click the play button at the top of the Debug panel which will launch an instance of Chrome in debug mode. Keep in mind your app should already be running from using ng serve earlier. In VS Code, you should see the Debug toolbar pop up.

With this up and running, you can set a breakpoint in your App.js. Open up your App.js and add a breakpoint inside of the render function by clicking in the gutter (to the left of the line numbers). Should look like this.

Now, refresh debugging by clicking the refresh button on the debugging toolbar. This should open your application again and trigger this breakpoin. You should be directed back to VS Code directly to the place where you set your breakpoint.

From here, you can set more breakpoints, inspect variables, etc. If you are interested in learning more about debugging JavaScript in general in either Chrome or VS Code you can check out Debugging JavaScript in Chrome and Visual Studio Code.

Again, if you're interested in learning more about VS Code, you'll definitely want to check out the upcoming Learn VS Code course.

If you have any follow up questions or comments, leave one below of find me on twitter @jamesqquick.

For video content, check out my YouTube Channel

Like this article? Follow @jamesqquick on Twitter

Sours: https://scotch.io/tutorials/debugging-create-react-app-applications-in-visual-studio-code
The New Way To Debug JavaScript in VS Code - No Extension Required

Browser debugger or extension to the browser debugger is the usual way of debugging Javascript-based web applications and Javascript-based frameworks like React, Angular, etc. For React-based apps, React Developer Tools is such an extension. There is nothing wrong with this approach of debugging. But having developed many java-based enterprise applications in previous years, I am someone who prefers to debug code inside my editor only. Visual Studio Code with its in-built debugging support for node.js runtime is perfect for this scenario. 

In this blog, we will take example of Filtered Product List application found on reactjs.org under Thinking in React section. This is a popular example for anyone learning React. As the main motive of this blog is to show how React App can be debugged from Visual Studio Code, we will not discuss how the application is built. We will mainly see how this application can be debugged from right inside the Visual Studio Code. 

If you do not have visual studio code already installed, it can be downloaded from here : Download Visual Studio Code

                                                                       React Filterable Product List Application

But as you can see, there seems to be a bug in the App above. When the checkbox saying “Only show product in stock” is clicked, it is showing products which are out of stock and not the products which are in stock. We have found a bug and we will debug and try to find out where it is. 


Importing Example Code

If you want to download this example code and run it inside visual studio yourself, then it can be taken from the GitHub URL: https://github.com/PranavManiar/thinking-in-react. Just import the folder in Visual Studio Code and you should be ready to go! (You will also have to install npm to run the code )


Installing Debugger for Chrome Extension

To debug the React Application, we first need to install Debugger for Chrome extension.

nstalling Debugger for Chrome Extension

                                                                    Installing Debugger for Chrome Extension

From the left panel select the extensions or use the shortcut (ctrl+shift+x) to open Extension view. Now type “chrome” in the search box. Out of several extensions that come up in the list, select Developer for Chrome

Click the Install button for Debugger for Chrome. After the installation is complete, reload to restart VS Code to activate the extension.


Configure the Chrome debugger

Before starting debugging, we first need to configure Chrome debugger. 
For configuring it, go to debug view by either clicking on Debug icon in the leftmost panel or using the shortcut (Ctrl+Shift+D). Now in the debug window, click on the gear button to create configuration file for your debugger. You will be asked to select an environment. Choose the Chrome  drop down. This will create file in a new . folder inside your project. Following is the configuration for both launching a website in debug mode or attach to a running instance. 


Setting Breakpoint

To set a break point in click on the gutter to the left of the line numbers. This will set a break point, which will be visible as a red circle.

Setting Breakpoint
                                                                                           Setting Breakpoint

Start the application by running command  . This will launch the website on  


Start Debugging Session

To start the debugging session, click on the green arrow in the debug view or the shortcut (F5). It will open a new Chrome window and load the web app there. Once we do any operation on web app which hits the breakpoint, code debugger will come into the picture. 
 

Start Debugging Session
                                                                                       Launching App in Debug Mode


Debugging 

Since we have put break point inside ProductTable’s render method, whenever our Product Table’s data will get changed, code will stop at the breakpoint.

We have seen that there was an issue with the “Only show products in stock”. So we will see what goes on in Product Table when we click on the checkbox. 

Debugging 
                                                                             Application pauses in chrome

Once we click on the checkbox, browser will show message that paused in Visual Studio Code. 
Inside editor, we can see that code execution is halted at the breakpoint.


                                                                                 Debugger View of Visual Studio Code

In the Debugger view :

- All variables are listed in Variable Section.
- We can add a watch for any variable/expression. Its value will be seen in watch section.
- Call stack till the current method is shown inside Call Stack Section
- All breakpoints are listed in Breakpoints section

While debugging, the variable’s value will also be shown when you hover over any variable. We can also drill down and expand the fields. In the above screenshot, the value of props object is shown. 

In the top center, debugging toolbar is shown while debugging the app. Following are the basic commands for the debugger: 

Step Over (F10
Step Into (F11)  
Step Out (Shift + F11)
Pause (F6)
Restart (Ctrl + Shift + F5)
Stop (Shift + F5)

Now after debugging the code, we can see that on line 47, we have put condition instead of if. If we change this and retest the application, then it starts to behave correctly. Only product in the stock will be shown when checkbox is clicked. 

While this is a very trivial example of debugging, it should give you a feel of what can be done with Visual Studio Code Debugger. If you are using webpack (most of us already do) together with your React app, then you can take the advantage of webpack’s HMR mechanism, which will enable you to have live editing and debugging using Visual Studio Code. 

Also, VS code debugger is not only limited to debugging React App, it can be used to debug any node.js runtime-based application.
Syntax highlighting, Super fast IntelliSense, Code navigation combined with debugging feature makes VS Code a very attractive editor for developing client-side application.  

Sours: https://www.zeolearn.com/magazine/debugging-react-apps-in-visual-studio-code

Now discussing:

Using React in VS Code

React is a popular JavaScript library developed by Facebook for building web application user interfaces. The Visual Studio Code editor supports React.js IntelliSense and code navigation out of the box.

welcome to react

Welcome to React

We'll be using the generator for this tutorial. To install and use the generator as well as run the React application server, you'll need the Node.js JavaScript runtime and npm (the Node.js package manager) installed. npm is included with Node.js which you can install from here.

Tip: To test that you have Node.js and npm correctly install on your machine, you can type and .

To install the generator, in a terminal or command prompt type:

This may take a few minutes to install. You can now create a new React application by typing:

where is the name of the folder for your application. This may take a few minutes to create the React application and install it's dependencies.

Let's quickly run our React application by navigating to the new folder and typing to start the web server and open the application in a browser:

You should see "Welcome to React" on in your browser. We'll leave the web server running while we look at the application with VS Code.

To open your React application in VS Code, open another terminal (or command prompt) and navigate to the folder and type :

Markdown Preview

In the File Explorer, one file you'll see is the application Markdown file. This has lots of great information about the application and React in general. A nice way to review the README is by using the VS Code Markdown Preview. You can open the preview in either the current editor group (Markdown: Open Preview) or in a new editor group to the side (Markdown: Open Preview to the Side). You'll get nice formatting, hyperlink navigation to headers, and syntax highlighting in code blocks.

README markdown preview

Syntax highlighting and bracket matching

Now expand the folder and select the file. You'll notice that VS Code has syntax highlighting for the various source code elements and, if you put the cursor on a parentheses, the matching bracket is also selected.

react bracket matching

IntelliSense

As you start typing in , you'll see smart suggestions or completions.

react suggestions

After you select a suggestion and type , you see the types and methods on the object through IntelliSense.

react intellisense

VS Code uses the TypeScript language service for it's JavaScript code intelligence and it has a feature called Automatic Type Acquisition (ATA). ATA pulls down the npm Type Declaration files () for the npm modules referenced in the .

If you select a method, you'll also get parameter help:

react parameter help

Go to Definition, Peek definition

Through the TypeScript language service, VS Code can also provide type definition information in the editor through Go to Definition () or Peek Definition (). Put the cursor over the , right click and select Peek Definition. A Peek window will open showing the definition from .

react peek definition

Press to close the Peek window.

Hello World!

Let's update the sample application to "Hello World!". Add the link to declare a new H1 header and replace the tag in with .

Once you save the file, the running instance of the server will update the web page and you'll see "Hello World!".

Tip: VS Code supports Auto Save, which by default saves your files after a delay. Check the Auto Save option in the File menu to turn on Auto Save or directly configure the user setting.

hello world

Debugging React

To debug the client side React code, we'll need to install the Debugger for Chrome extension.

Note: This tutorial assumes you have the Chrome browser installed. The builders of the Debugger for Chrome extension also have versions for the Safari on iOS and Edge browsers.

Open the Extensions view () and type 'chrome` in the search box. You'll see several extensions which reference Chrome.

debugger for chrome

Press the Install button for Debugger for Chrome. The button will change to Installing then, after completing the installation, it will change to Reload. Press Reload to restart VS Code and activate the extension.

Set a breakpoint

To set a breakpoint in , click on the gutter to the left of the line numbers. This will set a breakpoint which will be visible as a red circle.

set a breakpoint

Configure the Chrome debugger

We need to initially configure the debugger. To do so, go to the Debug view () and click on gear button to create a debugger configuration file. Choose Chrome from the Select Environment dropdown. This will create a file in a new folder in your project which includes configuration to both launch the website or attach to a running instance.

We need to make one change for our example: change the port from to . Your should look like this:

Ensure that your development server is running ("npm start"). Then press or the green arrow to launch the debugger and open a new browser instance. The source code where the breakpoint is set runs on startup before the debugger was attached so we won't hit the breakpoint until we refresh the web page. Refresh the page and you should hit your breakpoint.

hit breakpoint

You can step through your source code (), inspect variables such as , and see the call stack of the client side React application.

debug variable

The Debugger for Chrome extension README has lots of information on other configurations, working with sourcemaps, and troubleshooting. You can review it directly within VS Code from the Extensions view by clicking on the extension item and opening the Details view.

debugger for chrome readme

Linting

Linters analyze your source code and can warn you about potential problems before you run your application. The JavaScript language services included with VS Code has syntax error checking support by default which you can see in action in the Problems panel (View > Problems).

Try making a small error in your React source code and you'll see a red squiggle and an error in the Problems panel.

javascript error

Linters can provide more sophisticated analysis, enforcing coding conventions and detecting anti-patterns. A popular JavaScript linter is ESLint. ESLint when combined with the ESLint VS Code extension provides a great in-product linting experience.

First install the ESLint command line tool:

Then install the ESLint extension by going to the Extensions view and typing 'eslint'.

ESLint extension

Once the ESLint extension is installed and VS Code reloaded, you'll want to create an ESLint configuration file . You can create one using the extension's ESLint: Create 'eslintrc.json' File command from the Command Palette ().

create eslintrc

The command will create a file in your project root:

ESLint will now analyze open files and shows a warning in about 'App' being defined but never used.

App is unused

You can modify the ESLint rules and the ESLint extension provides IntelliSense in .

eslintrc IntelliSense

Let's add an error rule for extra semi-colons:

Now when you mistakenly have multiple semicolons on a line, you'll see an error (red squiggle) in the editor and error entry in the Problems panel.

extra semicolon error

Popular Starter Kits

In this tutorial, we used the generator to create a simple React application. There are lots of great samples and starter kits available to help build your first React application.

VS Code React Sample

This is a sample React application used for a demo at this year's //Build conference. The sample creates a simple TODO application and includes the source code for a Node.js Express server. It also shows how to use the Babel ES6 transpiler and then use webpack to bundle the site assets.

MERN Starter

If you'd like to see a full MERN (MongoDB, Express, React, Node.js) stack example, look at the MERN Starter. You'll need to install and start MongoDB but you'll quickly have a MERN application running. There is helpful VS Code-specific documentation at vscode-recipes which details setting up Node.js server debugging.

TypeScript React

If you're curious about TypeScript and React, you can also create a TypeScript version of the application. See the details at TypeScript-React-Starter on the TypeScript Quick Start site.

Angular

Angular is another popular web framework. If you'd like to see an example of Angular working with VS Code, check out the Chrome Debugging with Angular CLI recipe. It will walk you through creating an Angular application and configuring the file for the Debugger for Chrome extension.

Common Questions

Q: Can I get IntelliSense within declarative JSX?

A: Yes. For example, if you open the project's file, you can see IntelliSense within the React JSX in the method.

JSX IntelliSense

Sours: https://vscode.readthedocs.io/en/latest/nodejs/reactjs-tutorial/


819 820 821 822 823