DEV Community

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

Setting up a React Environment for ASP.NET MVC

Sung M. Kim on October 13, 2018

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 &am...
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!

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
 
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
 
jiaqizuo profile image
JiaqiZuo

I tried to create about.js for about.cshtml and followed the same steps for index.js and index.cshtml, but it did not work. So I am not thinking if there are additional steps that I need to do? Thanks in advanced!

Collapse
 
dance2die profile image
Sung M. Kim

Hi @jiaqizuo

What's error and do you have code snippets handy?

Collapse
 
jiaqizuo profile image
JiaqiZuo • Edited

So basically I just did the same things what you taught to about.js and about.cshtml, but it seems there is no thing to show up on the About Page

Collapse
 
oudoulj profile image
Jérôme Oudoul

First off, thank you for the great article : it's helping me a lot to configure ReactJS.NET within our ASP.NET MVC 4 website.
In step 4, you wrote :
Webpack outputs a bundle as ./Scripts/dist/Home/react/index.js
when I think you meant :
Webpack outputs a bundle as ./Scripts/dist/Home/react/bundle.js
Cheers!

Collapse
 
dance2die profile image
Sung M. Kim

Thank you, Jérôme 🙏 enjoying the post and spotting the error.

I've updated the post 🙂🤜

Collapse
 
guymalka profile image
guymalka

any idea how to create production verion (without node_modules folder) using the environment you created (mvc project)

Collapse
 
dance2die profile image
Sung M. Kim

When you generate a bundled JavaScript, you do not need to deploy the node_modules folder or add to the source control.

You could just deploy the bundled JavaScript in your production.

Or do you not want to have node_modules folder in the first place? If so you would need to use CDN scripts.

Collapse
 
guymalka profile image
guymalka • Edited

if i remove the "node_modules" from the environment , the project fall and i get error like Module build failed: Error: ENOENT: no such file or directory, open
'...node_modules\react\index.js'

Thread Thread
 
dance2die profile image
Sung M. Kim • Edited

Ah, I see what you mean.

I am sorry I made a mistake in the post so updated step 5. Install NPM packages to install react & react-dom as a dependency not as a dev dependency, which is not included in the final bundle.

So react & react-dom should be under dependencies as shown in package.json below.

{
    "version": "1.0.0",
    "name": "asp.net",
    "private": true,
    "scripts": {
        "dev": "webpack --mode development --watch",
        "build": "webpack"
    },
    "dependencies": {
        "react": "^16.5.2",
        "react-dom": "^16.5.2"
    },
    "devDependencies": {
        "@babel/cli": "^7.1.2",
        "@babel/core": "^7.1.2",
        "@babel/plugin-proposal-class-properties": "^7.1.0",
        "@babel/preset-env": "^7.1.0",
        "@babel/preset-react": "^7.0.0",
        "babel-loader": "^8.0.4",
        "browser-sync": "^2.26.3",
        "browser-sync-webpack-plugin": "^2.2.2",
        "webpack": "^4.20.2",
        "webpack-cli": "^3.1.2",
        "webpack-notifier": "^1.7.0"
    }
}
Thread Thread
 
guymalka profile image
guymalka

dont have any pack in devdependency

here is package.json

"name": "webbuildingoverhaul",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"@progress/kendo-data-query": "1.5.0",
"@progress/kendo-date-math": "1.3.2",
"@progress/kendo-drawing": "1.5.7",
"@progress/kendo-react-common": "2.4.0",
"@progress/kendo-react-dateinputs": "2.4.0",
"@progress/kendo-react-dropdowns": "2.4.0",
"@progress/kendo-react-excel-export": "2.6.1",
"@progress/kendo-react-grid": "2.4.0",
"@progress/kendo-react-inputs": "2.4.0",
"@progress/kendo-react-intl": "2.4.0",
"@progress/kendo-react-pdf": "2.4.0",
"@progress/kendo-theme-default": "2.56.0",
"babel-core": "6.26.3",
"babel-loader": "7.1.5",
"babel-preset-es2015": "6.24.1",
"babel-preset-react": "6.24.1",
"bootstrap": "4.1.3",
"css-loader": "0.28.11",
"kendo-ui-core": "2018.3.911",
"moment": "2.22.2",
"prop-types": "15.6.2",
"react": "16.5.0",
"react-alert": "4.0.4",
"react-alert-template-basic": "1.0.0",
"react-datetime": "2.16.3",
"react-dom": "16.5.0",
"react-redux": "5.0.7",
"react-router": "4.3.1",
"react-router-dom": "4.3.1",
"react-router-native": "4.3.0",
"react-transition-group": "2.4.0",
"redux": "3.7.2",
"redux-thunk": "2.3.0",
"restore": "0.3.0",
"style-loader": "0.19.1",
"webpack": "3.12.0",
"webpack-cli": "2.1.5",
"html-webpack-plugin": "3.1.0",
"webpack-dev-server": "3.1.8"
},
"devDependencies": {},
"scripts": {
"watch-test": "mocha --watch --reporter spec test",
"build-js": " reactify app.jsx | uglifyjs -mc > bundle.js",
"build": " webpack"
},
"author": "",
"license": "ISC"
}

Collapse
 
dance2die profile image
Sung M. Kim

I've also experienced issues with synchronization and blocked calls regularly, as well as build issues that I catch much sooner if I can see the build output.

...

I generally don't even bother with ide integration

I can empathize with your experience because
I've also been bitten badly trying to figure out why a page wasn't working properly as I assumed the site was rendered correctly without any build issues.

That's why I have a separate build script that'd just run webpack without watching the file change so I can fire up an one off build when I am paranoid 😀😄

Collapse
 
riadhoq profile image
Riadul Hoque

Thanks a lot! That was really easy to follow!

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome and thank you for the props, Riadul~

Collapse
 
nicolasguzca profile image
Nick

Thank you so much for this article! I was looking to start with React in .Net.

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome Nicolas.

But also consider creating React & Back-end in separate projects as discussed in this reddit post, Reaact and backend different or in same solution.

Collapse
 
nicolasguzca profile image
Nick

Great advice, thank you!

Collapse
 
markmbirira profile image
Mark Mbirira

Thanks for the nice simple article.

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Mark :)

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
 
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
 
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
 
yguang004 profile image
Yang guang

Nice article and help me a lot

Collapse
 
dance2die profile image
Sung M. Kim

Thank you. I am glad that it was helpful 🙂

Collapse
 
thejoezack profile image
Joe Zack

Great write up! That's a lot more to that than just running "create-react-app" so I appreciate your time figuring this out and writing it up (with screenshots!) so concisely!

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Joe 😀.

Your comment just made my day 🤜.

Collapse
 
socrates93 profile image
socrates93

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

Collapse
 
shadabahmed2422 profile image
shadabahmed2422

That was a nice article but can you add some rules before moving to production with this setup.

Collapse
 
technicallyty profile image
technicallyty

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

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
 
daniel662 profile image
Daniel Freitas

Thank you very much for the article.
Should I include in the project all the node_modules folder?

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome, Daniel.

You shouldn't include node_modules/ normally. But do include package-lock.json (or yarn-lock.json, if you are using yarn) as a lock file provide a way for others to create the same package structure.

Collapse
 
luisdev99 profile image
LuisDev99

did not work lmao, vs2019 here. It wont show me the content of react in the web app, but shows the other content

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