React with ASP.NET Core Series – Part 1: This is part 1 of a 5 parts React with ASP.NET Core series. This series will show you the setup necessary for building React single page application with routing and server-side rendering.
When I first started working on React, I struggled for quite a while in setting up the project correctly. Even though there were tons of examples, tutorials or boilerplate you can found on the Internet, they are either packing too many stuffs or assumed you know many technologies needed to get React to compile and execute. I was confused with all the terminologies, and not quite understand how all these packages and technologies worked together. I tried some tutorials step by step and they won’t even compile.
So this tutorial is intended for fresh starters who are new to React and wonder how to make it work with ASP.NET Core.
Certainly there is now a react template available from Visual Studio readily to run React with ASP.NET Core. However, there is a lot of meat packed in there and could be difficult to swallow.
Extra stuffs that we need
React components are written with additional syntax that would be stored as file with extension .jsx. However, browsers only know how to execute javascript. Therefore, we need some conversion to convert .jsx to .js. That’s when Babel and webpack come into play. Babel is a javascript transpiler (converts newer javascript syntax to javascript version that is browser-compatible) that converts .jsx to .js while webpack (a module bundler) will utilize Babel to do conversion and then bundle the converted React components and other necessary modules to form a single javascript file (webpack is capable of doing code-splitting and many other useful features, but that’s out of the scope of this tutorial).
We also need Nodejs to run webpack.
Note: there are other transpilers and module bundlers that can do a similar job. But Babel and webpack are my favorite, so I am gonna stick to them.
Get started
Goal: To get started with enabling React application to display a simple HelloWorld component.
Let’s create a new project of ASP.NET Core Web Application (under Installed > Visual C# when you click on ‘New Project’).
Use template Web Application (Model-View-Controller). Then build and run the new project should bring up your browser showing the demo page by Microsoft. We will use this template to add packages needed and React code to display ‘Hello world using React!’.
Install Nodejs
Visual Studio included an older version which could cause problems with newer version of webpack. Therefore, let’s install the latest version of Nodejs.
So let’s remove the default use of the older version included.
Go to Tools > Options > Projects and Solutions > Web Package Management > External Web Tools
Make sure $(VSINSTALLDIR)\Web\External is unchecked and most certainly this would save you a lot of scratch your head problems.
Restart Visual Studio to make sure new Nodejs is in place.
Install Npm modules
npm has a large registry of javascript libraries you can incorporate into your project. We will use that to install react, babel & webpack.
Let’s first create a package.json file. It’s the file that defines all the npm modules you need. Right click on your project, at the context menu, select Add > New Item. Then select file type Installed > Visual C# > ASP.NET Core > Web > npm Configuration File. The file package.json should look like below:
1 2 3 4 5 6 7 |
{ "version": "1.0.0", "name": "asp.net", "private": true, "devDependencies": { } } |
Let’s replace the file with the necessary modules as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{ "version": "1.0.0", "name": "asp.net", "private": true, "dependencies": { "react": "16.4.1", "react-dom": "16.4.1" }, "devDependencies": { "webpack": "4.15.1", "webpack-cli": "3.0.8", "aspnet-webpack": "3.0.0", "webpack-dev-middleware": "3.1.3", "babel-loader": "7.1.5", "babel-preset-react": "6.24.1", "babel-preset-env": "1.7.0", "babel-core": "6.26.3" } } |
These modules are the libraries to enable react, babel and webpack in your project. After the modification, save the file and your project will automatically download the specified modules under the folder called node_modules.
Create Simple React HelloWorld Component
Create a folder called ‘Scripts’ under the project and then inside ‘Scripts’ folder, Add New Item called ‘HelloWorld.jsx’ (type JSX File under Installed > Visual C# > Web)
1 2 3 4 5 6 7 |
import * as React from 'react'; export class HelloWorld extends React.Component { render() { return <div>Hello world using React!</div>; } } |
Setup webpack for bundling
First install a Visual Studio extension called Webpack Task Runner. Go to Tools > Extensions and Updates... > Online and search for ‘webpack’. You should then see Webpack Task Runner. Download and install it. You may need to save and quit Visual Studio to complete the installation.
webpack requires an entry file to tell what is in the bundle. Inside ‘Scripts’ folder, add another New Item called entry.jsx
1 2 3 4 5 |
import * as React from 'react'; import { render } from 'react-dom'; import { HelloWorld } from './HelloWorld.jsx'; render(<HelloWorld />, document.querySelector('body')); |
This simple entry file, bundled and executed at browser will replace the webpage with the text ‘Hello World!’
Next we create a configuration file for webpack. Add a New Item under project and select the type WebPack configuration File under Installed > Visual C# > Web. Populate the file as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
"use strict"; const path = require('path'); module.exports = { mode: 'development', target: 'web', entry: { bundle: "./Scripts/entry.jsx" }, output: { path: path.resolve(__dirname, 'wwwroot/dist'), publicPath: '/dist/', // needed for UseWebpackDevMiddleware() filename: "[name].js" }, module: { rules: [ { test: /\.jsx$/, loader: 'babel-loader', query: { presets: ['react', ['env', { 'targets': { 'browsers': '> 5%' }}]]}} ] }, resolve: { extensions: ['.jsx', '.js'] // with this, you don't need extension when importing modules } }; |
This tells webpack to use entry.jsx as the entry file, convert it using babel-loader and save the bundle (with all other necessary modules like react & react-dom) to the folder wwwroot/dist.
Update Startup.cs, insert following lines to the beginning of the method Configure(IApplicationBuilder app, IHostingEnvironment env)
1 2 3 4 |
if (env.IsDevelopment()) { app.UseWebpackDevMiddleware(); } |
This will enable the build process to include webpack compilation & bundling.
Test the bundle
Add the following line to the bottom of Views > Home > Index.cshtml
1 |
<script src="/dist/bundle.js"></script> |
Now run the app and you shall see the demo page replaced by ‘Hello world using React!’. Awesome, you are now running React with ASP.NET Core.
Note: bundle.js does not exist until you run the app. If you want to check out bundle.js before running the app, double click on Task Runner Explorer > Run - Development.
Example code for React with ASP.NET Core series – Part 1 is available at Github.
More Read
React with ASP.NET Core series – Part 2: React with Typescript, Get started with ASP.NET Core