React And Nodejs

Posted on  by admin
-->

Applies to: Visual Studio Visual Studio for Mac

With Visual Studio, you can easily create a Node.js project and use IntelliSense and other built-in features that support Node.js. In this tutorial, you create a Node.js web app project from a Visual Studio template. Then, you create a simple app using React.

In this tutorial, you learn how to:

  • Both Node.js and React.js are of JavaScript, yet both are completely different.
  • The main difference between Node.js and React.js is that Node.js is a back-end framework while React.js is used for user interface development for the app.
  • Yet, both have their cons and pros and unique use cases for mobile app development.
  • In this article, you will find the introduction of React JS and Node JS, their features, example for the app development and its difference.
  • Based on a detailed discussion on both the technologies, you can find the one you should use for your next software development.

Let's get started.

Node.js is one such framework that helps develop the back-end of applications with JavaScript. As per Google Chrome's V8 JavaScript engine powers, Node.js is more useful and lightweight.

Before you begin, here's a quick FAQ to introduce you to some key concepts:

  • Developers highly use it for event-driven and non-blocking I/O models.

    Specially to host APIs, access the database, and serve HTTP requests, developers use the Node.js framework.

  • Who uses Node.js?

    Node.js is used by the majority of companies and has multiple famous clients, such as Netflix, NASA, Trello, PayPal, LinkedIn, Walmart, Uber, Twitter, Yahoo, eBay, GoDaddy, and more.

  • Here we have who and why Node.js has evolved its framework of choice.

    If we talk about Netflix, they went through A/B testing to offer a reach experience to 93 million users.

  • And meanwhile, they faced some issues of conditional dependencies and app scalability.

    Here comes the role of Node.js to crack these issues; the company has chosen Node.js to offer fast speed and effective usage. As a result, Netflix has reduced startup time by 70%.

  • Single-threaded: Node.js framework is lightweight still more scalable compared to other frameworks because it operates a single-threaded design with event loopings.

    Overall, it helps to handle multiple requests compared to traditional servers like Apache HTTP Server. Open Source: Node.js works as open-source for code as it is ready to use for free and available for the developer to use.

Prerequisites

This tutorial requires the following prerequisites:

  • Enhanced Performance: If you want to develop an app with improved performance, choose Node.js.

    It helps the developers complete non-blocking functions that boost the app's performance.

    1. Scalability: Node.js is powerful and got the capability to scale up the app performance both horizontally and vertically.

    2. No Buffering: Applications developed with Node.js will show performance in blocks due to its callback function.

    So, the user receives the data faster and easily available with no waiting time for the operation to finish.

    1. It overall lowers the processing time, and thus no buffer on data.

    2. "As per the study and Node.js User Survey Report, most of 49.9% developers used Node.js and created it as most used frameworks, libraries, and tools in 2019.”.

  • React.js is another famous technology that is open-source code library.

    It is highly used to design the user interfaces or front-end web applications. React.js can improve the speed and offer a dependable platform to serve the front-end.

    Also, React.js is developed by Facebook and has been enhanced for better performance. Who are the people using React.js? Facebook, a known app that has allowed companies of all sorts, from content-driven websites like the New York times and Twitter as social media apps.

    It has served the best User Interface with the help of React.js. A website like Facebook, Twitter and other entirely relies on interaction with the user and uses a dynamic framework.

    1. Instagram, another associate of Facebook, is yet another illustration of an app created with React.js.

    2. Easy Maintenance: React.js is easy to maintain as its library is brilliant, and it re-uses any crucial system elements. It helps in solving any issue about the updating of the React.js framework.

Extensions: Along with the UI framework, React offers a combination of extensions that allows users to develop a complete application architecture.

Create a project

First, create a Node.js web app project.

  1. React.js extensions help in web development with the essential benefit of Flux and Redux.

  2. So, React, a famous framework, is known for developing cross-platform mobile apps. Better Performance: Any app will improve its performance with the React.js framework as it uses the Virtual Document Object Model (DOM).

    Stability of Code: React.js provides written code that is very stable due to its usage in the downward flow of data.

    JSX: JSX is one of the excellent features represented as a markup language closely resembling HTML. It’s parallel to the result that is a mix of XML and JavaScript.

  3. Virtual DOM: For a virtual DOM, a software app development company helps in DOM object with React.

    It makes a virtual duplicate of the real DOM because the virtual DOM is a one-way data-binding. Event Handling: React.js can apply its event system completely compliant with the W3C object model.

  4. And specially manufactured event examples will shield all native events.

    • So as a whole, it combines a native event with a cross-browser interface. React is known for its functionality and multiple User Interface benefits.

    • It also helps in modularity and separations of concerns as the benefits. But it is essential to know that React.js is not a framework. React, which is also learned as React.js or ReactJS, is an open source and free JavaScript library.

      It is highly used for developing user interfaces or UI components for any app. React allows you to reuse its elements multiple times in a single web application. The favor of both Node.js and React.js is unquestioned as we see there are pros of both technologies.

    • Both of these frameworks work best for software development as both have huge communities backing them up.

      If you are looking for an IT outsourcing company in India for your app development, we will help you choose the right framework for your project. Here are some key takeaways:.

    • Node.js offers speed, scalability, and better performance for app development. So, it seems Node.js is more suitable for an assortment of tasks.

    • With React, it is seamless to develop lightweight web and mobile apps. As one can run React on the server-side, and the virtual DOM will be rendered, it is highly used for the regular web page.

      Both Node and React have vibrant and significant community support, so they can be used per the business requirements.

  1. You can make the front-end of the software app development with React and the back-end with Node js, as Netflix accomplished.

  2. Create a new project.

    Press Esc to close the start window. Type Ctrl + Q to open the search box, type Node.js, then choose Blank Node.js Web Application - JavaScript. (Although this tutorial uses the TypeScript compiler, the steps require that you start with the JavaScript template.)

    In the dialog box that appears, choose Create.

    If you don't see the Blank Node.js Web Application project template, you must add the Node.js development workload. For detailed instructions, see the Prerequisites.

    Visual Studio creates the new solution and opens your project.

    (1) Highlighted in bold is your project, using the name you gave in the New Project dialog box. In the file system, this project is represented by a .njsproj file in your project folder. You can set properties and environment variables associated with the project by right-clicking the project and choosing Properties (or press Alt + Enter). You can do round-tripping with other development tools, because the project file does not make custom changes to the Node.js project source.

    (2) At the top level is a solution, which by default has the same name as your project. A solution, represented by a .sln file on disk, is a container for one or more related projects.

    (3) The npm node shows any installed npm packages. You can right-click the npm node to search for and install npm packages using a dialog box or install and update packages using the settings in package.json and right-click options in the npm node.

    (4) package.json is a file used by npm to manage package dependencies and package versions for locally installed packages. For more information, see Manage npm packages.

    (5) Project files such as server.js show up under the project node. server.js is the project startup file and that is why it shows up in bold. You can set the startup file by right-clicking a file in the project and selecting Set as Node.js startup file.

  1. Open Visual Studio.

  2. Create a new project.

    From the top menu bar, choose File > New > Project. In the left pane of the New Project dialog box, expand JavaScript, then choose Node.js. In the middle pane, choose Blank Node.js Web Application, type the name NodejsWebAppBlank, then choose OK.

    If you don't see the Blank Node.js Web Application project template, you must add the Node.js development workload. For detailed instructions, see the Prerequisites.

    Visual Studio creates the new solution and opens your project.

    (1) Highlighted in bold is your project, using the name you gave in the New Project dialog box. In the file system, this project is represented by a .njsproj file in your project folder. You can set properties and environment variables associated with the project by right-clicking the project and choosing Properties (or press Alt + Enter). You can do round-tripping with other development tools, because the project file does not make custom changes to the Node.js project source.

    (2) At the top level is a solution, which by default has the same name as your project. A solution, represented by a .sln file on disk, is a container for one or more related projects.

    (3) The npm node shows any installed npm packages. You can right-click the npm node to search for and install npm packages using a dialog box or install and update packages using the settings in package.json and right-click options in the npm node.

    (4) package.json is a file used by npm to manage package dependencies and package versions for locally installed packages. For more information, see Manage npm packages.

    (5) Project files such as server.js show up under the project node. server.js is the project startup file and that is why it shows up in bold. You can set the startup file by right-clicking a file in the project and selecting Set as Node.js startup file.

Add npm packages

This app requires the following npm modules to run correctly:

  • react
  • react-dom
  • express
  • path
  • ts-loader
  • typescript
  • webpack
  • webpack-cli

To install a package:

  1. In Solution Explorer, right-click the npm node and select Install New npm Packages.

  2. In the Install New npm Packages dialog box, search for the react package, and select Install Package to install it.

    In the Install New npm Packages dialog box, you can choose to install the most current package version or to specify a version. If you choose to install the current versions, but run into unexpected errors later, try installing the exact package versions listed in the next step.

    The Output window in the Visual Studio lower pane shows package installation progress. Open the Output window by selecting View > Output or pressing Ctrl+Alt+O. In the Show output from field of the Output window, select Npm.

    When installed, the react package appears under the npm node in Solution Explorer.

    The project's package.json file updates with the new package information, including the package version.

Instead of using the UI to search for and add the rest of the packages one at a time, you can paste the required package code into package.json.

  1. From Solution Explorer, open package.json in the Visual Studio editor. Add the following dependencies section before the end of the file:

    If the file already has a dependencies section, replace it with the preceding JSON code. For more information on using the package.json file, see package.json configuration.

  2. Press Ctrl+S or select File > Save package.json to save the changes.

  3. In Solution Explorer, right-click the npm node in your project and select Install npm Packages.

    This command runs the npm install command directly to install all the packages listed in packages.json.

    Select the Output window in the lower pane to see installation progress. Installation might take a few minutes, and you might not see results immediately. Make sure that you select Npm in the Show output from field in the Output window.

    After installation, the npm modules appear in the npm node in Solution Explorer.

    Note

    You can also install npm packages by using the command line. In Solution Explorer, right-click the project name and select Open Command Prompt Here. Use standard Node.js commands to install packages.

Add project files

Next, add four new files to your project.

  • app.tsx
  • webpack-config.js
  • index.html
  • tsconfig.json

For this simple app, you add the new project files in the project root. For most apps, you add the files to subfolders and adjust relative path references accordingly.

  1. In Solution Explorer, select the project name and press Ctrl+Shift+A, or right-click the project name and select Add > New Item.

  2. In the Add New Item dialog box, choose TypeScript JSX File, type the name app.tsx, and select Add or OK.

  3. Repeat these steps to add a JavaScript file named webpack-config.js.

  4. Repeat these steps to add an HTML file named index.html.

  5. Repeat these steps to add a TypeScript JSON Configuration File named tsconfig.json.

Add app code

  1. In Solution Explorer, open server.js and replace the existing code with the following code:

    The preceding code uses Express to start Node.js as your web application server. The code sets the port to the port number configured in the project properties, which by default is 1337. If you need to open the project properties, right-click the project name in Solution Explorer and select Properties.

  2. Open app.tsx and add the following code:

    The preceding code uses JSX syntax and React to display a message.

  3. Open index.html and replace the body section with the following code:

    This HTML page loads app-bundle.js, which contains the JSX and React code transpiled to plain JavaScript. Currently, app-bundle.js is an empty file. In the next section, you configure options to transpile the code.

Configure webpack and TypeScript compiler options

Next, you add webpack configuration code to webpack-config.js. You add a simple webpack configuration that specifies an input file, app.tsx, and an output file, app-bundle.js, for bundling and transpiling JSX to plain JavaScript. For transpiling, you also configure some TypeScript compiler options. This basic configuration code is an introduction to webpack and the TypeScript compiler.

  1. In Solution Explorer, open webpack-config.js and add the following code.

    The webpack configuration code instructs webpack to use the TypeScript loader to transpile the JSX.

  2. Open tsconfig.json and replace the contents with the following code, which specifies the TypeScript compiler options:

    The code specifies app.tsx as the source file.

  3. Press Ctrl+Shift+S or select File > Save All to save all changes.

Transpile the JSX

  1. In Solution Explorer, right-click the project name and select Open Command Prompt Here.

  2. In the command prompt, enter the following webpack command:

    node_modules\.bin\webpack ./app.tsx --config webpack-config.js

    The command prompt window shows the result.

    If you see any errors instead of the preceding output, you must resolve them before your app will work. If your npm package versions are different than the versions this tutorial specifies, that can cause errors. One way to fix errors is to use the exact versions shown in the earlier step.

    Also, if one or more package versions are deprecated and result in an error, you might need to install a more recent version to fix errors. For information on using package.json to control npm package versions, see package.json configuration.

  3. In Solution Explorer, right-click the project node and select Add > Existing Folder.

  4. Select the dist folder, and then select Select Folder.

    Visual Studio adds the dist folder, which contains app-bundle.js and app-bundle.js.map, to the project.

  5. Open app-bundle.js to see the transpiled JavaScript code.

  6. If prompted whether to reload externally modified files, select Yes to All.

Anytime you make changes to app.tsx, you must rerun the webpack command. To automate this step, you can add a build script to transpile the JSX.

Add a build script to transpile the JSX

Visual Studio versions starting with Visual Studio 2019 require a build script. Instead of transpiling JSX at the command line, as shown in the preceding section, you can transpile JSX when building from Visual Studio.

  1. Open package.json and add the following section after the dependencies section:

  2. Save your changes.

Run the app

  1. In the Debug toolbar, select either Web Server (Microsoft Edge) or Web Server (Google Chrome) as the debug target.

    If you know your preferred debug target is available on your machine, but it doesn't appear as an option, select Browse With from the debug target dropdown list. Select your default browser target in the list, and select Set as Default.

  2. To run the app, press F5, select the green arrow button, or select Debug > Start Debugging.

    A Node.js console window opens that shows the debugger listening port.

    Visual Studio starts the app by launching the startup file, server.js.

  3. Close the browser and console windows.

Set a breakpoint and run the app

Breakpoints are the most basic and essential feature of reliable debugging. A breakpoint indicates where Visual Studio should suspend your running code. You can then observe variable values, memory behavior, or whether a branch of code is running.

  1. In server.js, click in the gutter to the left of the staticPath declaration to set a breakpoint:

  2. To run the app, press F5 or select Debug > Start Debugging.

    The debugger pauses at the breakpoint you set, with the current statement highlighted. 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.

  3. To continue running the app, press F5, select Continue in the Debug toolbar, or select Debug > Continue.

    If you want to use the Chrome Developer Tools or F12 Tools for Microsoft Edge, press F12. You can use these tools to examine the DOM and interact with the app by using the JavaScript Console.

  4. Close the browser and console windows.

Set and hit a breakpoint in the client-side React code

In the preceding section, you attached the debugger to server-side Node.js code. To attach to and hit breakpoints in the client-side React code, you have to attach the debugger to the correct process. Here's one way to enable a browser and attach a process for debugging.

Enable the browser for debugging

You can use either Microsoft Edge or Google Chrome. Close all windows for the target browser. For Microsoft Edge, also shut down all instances of Chrome. Because both browsers share the Chromium code base, shutting down both browsers gives the best results.

Other browser instances can prevent the browser from opening with debugging enabled. Browser extensions might prevent full debug mode. You might need to use Task Manager to find and end all running Chrome instances.

To start your browser with debugging enabled:

  1. Select Browse With from the dropdown list in the Debug toolbar.

  2. On the Browse With screen, with your preferred browser highlighted, select Add.

  3. Enter the --remote-debugging-port=9222 flag in the Arguments field.

  4. Give the browser a new friendly name such as Edge with debugging or Chrome with debugging, and then select OK.

  5. On the Browse With screen, select Browse.

  • Alternatively, you can open the Run command by right-clicking the Windows Start button, and enter:

    msedge --remote-debugging-port=9222

    or

    chrome.exe --remote-debugging-port=9222

For this scenario, use Chrome.

  1. Close all Chrome browser windows.

    Other browser instances can prevent the browser from opening with debugging enabled. Browser extensions might prevent full debug mode. You might need to open Task Manager to find all running Chrome instances.

  2. Start your browser with debugging enabled.

    Open the Run command from the Windows Start button (right-click and choose Run), and enter the following command:

    chrome.exe --remote-debugging-port=9222

The browser starts with debugging enabled. The app isn't running yet, so the browser page is empty.

Attach the debugger to client-side script

  1. In the Visual Studio editor, set a breakpoint in either the app-bundle.js or app.tsx source code.

    • For app-bundle.js, set the breakpoint in the render() function. To find the render() function in the app-bundle.js file, press Ctrl+F or select Edit > Find and Replace > Quick Find, and enter render in the search field.

    • For app.tsx, set the breakpoint inside the render() function, on the return statement.

      If you set the breakpoint in app.tsx, also update webpack-config.js to replace the following code, and save your changes.

      Replace this code:

      With this code:

      This development-only setting enables debugging in Visual Studio. By default, webpack references in the source map file include the webpack:/// prefix, which prevents Visual Studio from finding the source file app.tsx. This setting overrides the generated references in the source map file, app-bundle.js.map, when building the app. Specifically, this setting changes the reference to the source file from webpack:///./app.tsx to ./app.tsx, which enables debugging.

  2. Select your target browser as the debug target in Visual Studio, and then press Ctrl+F5, or select Debug > Start Without Debugging, to run the app in the browser.

    If you created a debugging-enabled browser configuration with a friendly name, choose that browser as your debug target.

    The app opens in a new browser tab.

  3. Select Debug > Attach to Process, or press Ctrl+Alt+P.

    Tip

    Once you attach to the process the first time, you can quickly reattach to the same process by selecting Debug > Reattach to Process or pressing Shift+Alt+P.

  4. In the Attach to Process dialog box, get a filtered list of browser instances that you can attach to.

    Make sure the correct debugger for your target browser, JavaScript (Chrome) or JavaScript (Microsoft Edge - Chromium), appears in the Attach to field. Type chrome or edge in the filter box to filter the results.

    In Visual Studio 2017, choose Webkit code in the Attach to field. Type chrome in the filter box to filter the search results.

  5. Select the browser process with the correct host port, localhost in this example. The port number 1337 or localhost might also appear in the Title field to help you select the correct process.

  6. Select Attach.

    The following example shows an Attach to Process window for the Microsoft Edge browser.

    When the debugger attaches correctly, 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.

    Tip

    If the debugger doesn't attach and you see the message Unable to attach to the process. An operation is not legal in the current state., use 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.

  7. Because the code with the breakpoint already executed, refresh your browser page to hit the breakpoint.

    Depending on your environment, browser state, and which steps you followed earlier, you might hit the breakpoint in app-bundle.js or its mapped location in app.tsx. Either way, you can step through code and examine variables.

    While the debugger is paused, you can examine your app state by hovering over variables and using debugger windows. To step through code, press F11 or select Debug > Step Into, or press F10 or select Debug > Step Over. To continue running the code, press F5 or select Continue. For more information on basic debugging features, see First look at the debugger.

    • If you can't break into code in app.tsx, retry using Attach to Process to attach the debugger as described in the previous steps. Make sure that your environment is set up correctly:

      • Close all browser instances, including Chrome extensions, by using the Task Manager. Make sure you start the browser in debug mode.

      • Make sure your source map file includes a reference to ./app.tsx and not webpack:///./app.tsx, which prevents the Visual Studio debugger from locating app.tsx.

      Or, try using the debugger; statement in app.tsx, or set breakpoints in the Chrome Developer Tools or F12 Tools for Microsoft Edge instead.

    • If you can't break into code in app-bundle.js, remove the source map file, app-bundle.js.map.

Next steps