DEV Community

Cover image for Setting up a React Environment for ASP.NET MVC
Sung M. Kim
Sung M. Kim

Posted on • Originally published at slightedgecoder.com on

Setting up a React Environment for ASP.NET MVC

Photo by Zoltan Tasi on Unsplash

I had a chance to update a legacy ASP.NET MVC website using AngularJS (yes, the first version) to use Webpack & Babel 7 (which used to import AngularJS files using script tags).

Previous post Setting up an ES6 Environment for ASP.NET MVC 5 was a bit outdated as it was using older version of babel and webpack, so I decided write more concise post to get started with the newest libraries.

As I have moved onto React, I will show you how to set up React environment for ASP.NET MVC 5.

๐Ÿง Prerequisite

I will assume that you are familiar with NPM & Webpack,

so I wonโ€™t go into too much details on what each option in NPM & Webpack.

๐Ÿ‘ฃ Setup Steps

  1. Create an ASP.NET MVC web site
  2. Create & configure NPM configuration file (package.json)
  3. Create & configure Babel configuration file (.babelrc)
  4. Create & configure Webpack configuration file (webpack.config.js)
  5. Install NPM packages
  6. Install Visual Studio Extensions (NPM Task Runner)

1. Create an ASP.NET MVC web site

Create a new ASP.NET MVC project (choose a choice of your .NET framework).

Create a new ASP.NET MVC Project

And select a template.

MVC Template

2. Create & configure NPM configuration file (package.json)

Add a new item in the project root.

Add New Itemโ€ฆ

Create NPM configuration file, package.json.

npm Configuration File

And add a script section. And package.json would initially look like the following.

3. Create & configure Babel configuration file (.babelrc)

Add a new file named .babelrc in the same directory as package.json file created in the previous step.

And add following babel options.

4. Create & configure Webpack configuration file (webpack.config.js)

Create a file named webpack.config.js in the project root (same location as package.json & .babelrc) & configure it as shown below.

Webpack outputs a bundle as ./Scripts/dist/Home/react/bundle.js so letโ€™s add the script in View\Home\Index.cshtml razor file.

Bundle Script Tag

5. Install NPM packages

Now letโ€™s install NPM packages to enable latest JavaScript and React syntax.

6. Install Visual Studio Extensions (NPM Task Runner)

This is an optional step but to make our lives easier, letโ€™s install a Visual Studio extension, NPM Task Runner for running NPM scripts from Visual Studio.

NPM Task Runner Extension

โš› Letโ€™s write some React code

Now we are ready to write a React script using the latest JavaScript syntax (ES6+).

Letโ€™s add an entry point for React in Views\Home\Index.cshtml file by deleting everything except ViewBag.Title section and add <div id="app"></div>.

Now we have an entry point, letโ€™s write a simple React file index.js under Scripts\Home\react directory.

index.js

๐Ÿƒโ€ Transpiling and Running

You could run the dev script within package.json file but letโ€™s use the NPM task runner to make the life easier.

Open the โ€œTask Runner Explorerโ€ by right clicking on package.json file in the project root.

Open Task Runner Explorer

Start dev script (double click), which monitors the changes in index.js.

Start โ€œdevโ€ script by double clicking on it

To enable browser-sync, you need copy a script generated by browser-sync message in _Layout.cshtml under Shared folder near end of </body> tag.

Copy Browser-sync Script

And lastly, letโ€™s run ASP.NET from Visual Studio to see the result.

Start ASP.NET MVC

โ™ป Reloading Browser Automatically

Youโ€™ve installed browser-sync* packages so as you change your code, the browser will reload automatically upon saving.

browser-sync at work

๐Ÿ‘‹ Parting Words

In this post Iโ€™ve assumed that you know the basics of NPM & Webpack so skipped much of details so that you can easily get up and running.

Please refer to documentations linked in-line in the post if you want to understand how each step works and to troubleshoot should you run into an issue.

Source code is available on GitHub.

The post Setting up a React Environment for ASP.NET MVC appeared first on Sung's Technical Blog.

Latest comments (46)

Collapse
 
ntkiet99 profile image
Nguyแป…n Tuแบฅn Kiแป‡t

I have a problem with react routing. When I refresh the page, it gives an error that can't load.

Collapse
 
kratos2333 profile image
kratos2333 • Edited

Hi Kim, thanks for the informative post, much appreciate this. I got an issue when I deploy my mvc react application to the IIS server. As IIS will put a virtual path as the project root so the url will be server/myApp (server deployment) instead of localhost/ (local test). This will break many things like need to be to make it works on IIS server. Also http controller call like axios.post('/someController/someMethod') needs to be axios.post('/myApp/someController/someMethod'). Any suggestion on how to fix these path issues ? Thanks in advance

Collapse
 
technicallyty profile image
technicallyty

is there a way to get this to work with .jsx files?

Collapse
 
technicallyty profile image
technicallyty

Article says Webpack outputs a bundle as ./Scripts/dist/Home/react/bundle.js so letโ€™s add the script in View\Home\Index.cshtml razor file.

but then the picture below it shows it being added to _Layout.cshtml. Is this just a typo?

Collapse
 
tanchiencuoc profile image
T-T

Thanks to Sung M. Kim. The post is very detail.

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome & thanks for the comment~

Collapse
 
abimr profile image
abimr • Edited

Thanks for your tutorial! I now have a non-trivial React app in an ASP.NET MVC 5 project.

But now I need to be able debug the React app from VSCode/Chrome.

My webpack entrypoint is ./Scripts/react/index.jsx. The output is ./Scripts/dist/react/bundle.js. What should be my "webRoot" and "sourceMapPathOverrides" values in .vscode/launch.json? Am I missing other values?

  {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Chrome",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:23042",
        "webRoot": "${workspaceFolder}/Scripts/react",
        "sourceMapPathOverrides": {
          "webpack:///Scripts/react/*": "${webRoot}/*"
        }
      }
    ]
  }

Collapse
 
socrates93 profile image
socrates93

You can't imagine how much I thank you for this post. Thank you so much!!

Collapse
 
cvannor profile image
Curtis Vannor

Hi,

Great tutorial. However, I'm getting an ERR_SSL_PROTOCOL_ERROR where I add in the script for browsersync. Any ideas?

Thanks

Collapse
 
webatxcent profile image
Bill Butler

Hi, I tried out your process using VS2019, step by step and got the following error. Was hoping you might nudge me in the right direction :). [I am a relative newbie with npm]

ERROR in ./Scripts/Home/react/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: d:\Docs\Scratch\ReactTest\Web\Scripts\Home\react\index.js: Unexpected token (5:4)

  3 |
  4 | const App = () => (
> 5 |     <>
    |     ^
  6 |         <h1>React in ASP.NET MVC!</h1>
  7 |         <div>Hello React World</div>
  8 |     </>
    at Parser.raise (d:\Docs\Scratch\ReactTest\Web\node_modules\@babel\parser\lib\index.js:6400:17)
...
Collapse
 
dance2die profile image
Sung M. Kim • Edited

Hi Bill.

I am sorry it's because the code snippet is out of sync from the instruction. You might want to use React.Fragment instead of <>...</> because it's a syntatic sugar (you'd need to set up plugin-transform-react-jsx for that syntax to work, which is not set up in this article.)

As a workaround, you can use React.Fragment directly as shown below (I've also updated the gist to reflect the change).

import React from 'react';
import { render } from 'react-dom';

const App = () => (
    <React.Fragment>
        <h1>React in ASP.NET MVC!</h1>
        <div>Hello React World</div>
    </React.Fragment>
);

render(<App />, document.getElementById('app'));
Collapse
 
webatxcent profile image
Bill Butler

Thanks so much for the quick reply.
That didn't change the outcome. Same error unexpected token.

I did note that the first line in the index.js file

import React from 'react';

was reporting an Intellisense error: "(js) cannot use imports, exports, or module augmentations when '--module' is 'none'"
Could this be a contributing factor.

Collapse
 
daniel662 profile image
Daniel Freitas • Edited

I start dev script in the task runner and it works very good, but only once. When I edit index.js and save it, it doens't recompile the file and I need to run dev again every time. Do you think I'am doing some thing worng?

Collapse
 
daniel662 profile image
Daniel Freitas

Justo solved by adding the following lines in the webpack.config.js file:

watchOptions: {
poll: 1000 // Check for changes every second
}

Collapse
 
dance2die profile image
Sung M. Kim

Thanks for the update & the fix, Daniel~

I honestly moved away from using React within ASP.NET MVC, so wasn't aware of how to deal with it :)

Thread Thread
 
vroland1 profile image
Tory Roland

Out of curiosity, have you moved away from using React with .NET MVC for a particular reason or have you just become interested in other things? My team wants to implement a JavaScript technology to build out some parts of our site that might be a pain otherwise and I have been learning React because it seemed like a good fit. I know everything is dependent on the project at hand, but if there are general drawbacks in your opinion I would be interested in hearing. Thanks for this article it was very useful!

Thread Thread
 
dance2die profile image
Sung M. Kim

Hi Tory, check out the replies below.

have you moved away from using React with .NET MVC for a particular reason or have you just become interested in other things?

Tooling support for classic ASP.NET MVC (I haven't used ASP.NET Core) has been subpar (hot reloading was buggy, requireing manual refresh & new JavaScript syntax was flagged as erroneous, etc).

And also following JamStack, having a separate API server with a pure React front-end helped to separate responsibilities.

I can't seem to find the post(was it a forum?) now, but MS wasn't focusing on making SPA easier to develop few years ago so I moved away.

Thread Thread
 
vroland1 profile image
Tory Roland

Thanks for your perspective on this. Hoping to make the switch to .NET Core sometime soon and it seems like it is better suited, going to the Live 360 conference later this month and will hopefully get more information. Have a good one!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.