Getting started on ASP.NET Core & React – episode 03

Getting started on ASP.NET Core & React – episode 03


  1. Episode 1 – Introduction
  2. Episode 2 – Backend / Infrastructure
  3. Episode 3 – Frontend Setup (you are here)
  4. Episode 4 – Data flow
  5. Episode 5 – Tests / Security
  6. Episode 6 – It’s your turn
  7. Episode 7 – migrate from ASP.NET Core 1.1 to 2.0


What’s up, back-end master? Did you finish previous episode with fully working application, with configured database and tested accounts system? I hope so, because now it’s time for the front-end! As you may know from our introduction post, front-end of our application will be mostly based on React. But that’s not all! We are also going to use TypeScript 2, SASS, Webpack 2 and – as our package manager – npm. There will be a lot of cool stuff to learn from this episode and please keep in mind that all of these tool are used on a daily basis by industry leaders – you won’t waste your time by looking at some legacy solutions used in 2017 by no one. Being ‘on the edge’ is one of our top priorities during this course.

To-do list for this episode:

  1. Package manager configuration
  2. Directory structure for the front-end
  3. Your first React / TypeScript / SASS component
  4. Introducing Webpack
  5. Wrapping all together

1. Package manager configuration

As you may know, in programming we often use already existing solutions to solve our own problems and satisfy needs of the projects. Many tools help us reduce time we would need to spend working on i.e. authorization, security or look of our project, but using so called ‘third party solutions’ isn’t 100% free from the project maintenance perspective. In fact, owners of the project are getting more and more dependent on them.

Is there a way to introduce external dependencies in our project without ruining compatibility between everything we’ve been building so long? Of course – to track all tools, libraries and frameworks we’d like to use along with their versions we can use things called package managers.

If you’re familiar with .NET you may know something like that – it’s called NuGet. NuGet is a central repository and at the same time package manager for all .NET based solutions. For the front-end we can use something similar – node package manager (npm) I’m sure that some of you remember that we were talking about npm in our post related to Node.JS, but if you want to read an official introduction it can be found here.

To start using npm in our project we need two things – one is installing Node.JS, and second is cleaning up our SoftwareHouse.Web directory from files related to another front-end package manager – bower.

First one is straightforward – you need to go to the Node.JS website, visit Downloads section, download and install version 6.9.5 and check if commands like node and npm are available from your console / terminal.

You check both things in this way:

Looks good, time for the second step.

What about Bower? Why do we need something different than that? Bower is the default package management tool used in ASP.NET Core templates (so far, but I guess it will change soon). Idea of using bower came from days when there was a strict separation between client-side (packages managed by bower) and server-side (packages managed by npm) JavaScript. After a number of tweaks in npm front-end community moved to more unified solution with just one package manager and npm with it’s package.json file is now something like industry standard.

To clean our project from bower you need to follow steps from list below:

  1. Remove .bowerrc file from SoftwareHouse.Web directory
  2. Remove bower.json file from SoftwareHouse.Web directory
  3. Remove everything from wwwroot directory, but don’t remove itself
  4. If you are working with git repository (like we do) you can go to .gitignore file and uncomment (remove hash) line with wwwroot – just change #wwwroot to wwwroot. We don’t want to track content of this directory, and at the end of this post you’ll see why.

Now we can start using npm to track dependencies in our project. To do this we need one basic file – package.json – you can create it manually or execute command npm init from command line in main directory of our project. Basic structure of package.json should look like this:

At the top we have some metadata about our project like name, version and description, next there is empty section called scripts, then two sections used to track installed dependencies and the last one called engines to define proper version of Node with should be used during work with our project.

We can install first few core dependencies using command line or Visual Studio IDE (define desired packages and their versions in dependencies section in package.json, then right click on Dependencies/npm folder and click restore packages).

From command line which I prefer you can execute given command:

npm install react react-dom bootstrap jquery –save

You can open package.json file and see that under dependencies section first four packages (React, ReactDOM, jQuery and Bootstrap) have been defined with the newest available versions (flag –save caused update in package.json – just in case, it’s double hyphen before save). Now do the same with first few tools / utils:

npm install typescript @types/react @types/react-dom webpack –save-dev

It may take a while now, so be patient 😉

Ready? Congratulations! You’ve just installed webpack, typescript and type definitions for React in our project! All these things will be described later, but for sure it’s a good start. Here you can see that used flag was –save-dev – these dependencies aren’t core from our project’s perspective so they don’t have to be placed under dependencies section (devDependencies will be updated instead).

2. Directory structure

Directory structure for our front-end will probably expand in later episodes, but now we’d like to start with something really simple.

First, let’s start with root directory – on the same level as folders like Controllers and Data please create one called Frontend. Inside we’re are going to keep folders dedicated to each page in our application (if needed), so just for demo purposes first one can be called Homepage. Pages can contain various types of components, so first folder inside ‘page folder’ will be called Components. Later there might also be folders for non-component parts of the code, but we do only as much as we need for now. Finally, let’s create dedicated directory for our first component called Demo. Our structure should look like this: /Frontend/Homepage/Components/Demo.

If you are here it means that you are ready for your first React based component. Let’s go!

3. Your first React / TypeScript / SASS component

First question – why do we even need something like React components in our front-end codebase? Can’t we just use things like vanilla JavaScript or plain old jQuery?

Answer could be placed in separate post, but I’ll try to give you a few hints to explain situation on the front-end in 2017 based on it’s history over the years:

  1. At the beginning there was plain old DOM – a recipe for representing parts of the documents (websites) as a tree with nodes. Unfortunately, for many years there was no such thing as unified DOM – different implementations of it in different browsers caused many problems for front-end developers in the past.
  2. Libraries like jQuery were created to provide unified, cross-browser way of manipulating DOM structure – they gave us an API to navigate through it and change it’s structure by using defined selectors. However, it was in fact just a tool for nodes manipulation, not a solution for application architecture. That’s why projects heavily based on jQuery had often mixed UI and business logic layers. Developers were trying to figure out how to create maintainable applications based on jQuery and similar libraries.
  3. End-to-end frameworks like Knockout and later Angular gained in popularity because they were trying to cover all areas related to creating mature applications – they brought concepts from back-end programming like MVVM, MVC and many others to the screens of front-end developers. Front-end applications started looking serious.

In this really short overview of the front-end history I’ve tried to explain you why we moved from things like vanilla JS and operations on ‘raw’ DOM to frameworks like i.e. Angular. Last question is – why components?

Basically, components help us to write our front-end in a more ‘granular’ way.

With previous approaches based on i.e. controllers or view-models it was so easy to create big chunks of JavaScript code responsible for everything on a given page. Component-based approach looks much better – components should have well-defined responsibility, they can have scoped styles applied, they should be reusable and independent as much as possible and data flow inside them should be predictable. You’ll see how this can be achieved later in this post.

Now it’s time to introduce our core front-end technologies.

React (

‘It’s just a view’, ‘Lighter Angular’, ‘The best front-end tool I’ve ever seen’ – React can be described in many ways. For us it will be just a library for building user interfaces.

We choose React because of it’s ability to extend view layer of apps based on server-side routing. It’s super light and very fast, so it should fit perfectly into our front-end space.

We’ll cover the most important features of React during work with our application, but you should definitely check the official introduction to it on the author’s site – right there. Concepts like components, unidirectional data flow, and JSX format might be new for you, but don’t worry – with step-by-step approach to learning new things everything will be possible to understand – just give it some time and be patient.

TypeScript (

Let the TypeScript homepage speak for us – ‘TypeScript is a typed superset of JavaScript that compiles to plain JavaScript‘.

Some of you might be surprised that we use TypeScript along with React, but trust us – it just works. We’ll write our components using the best features of this language like lambdas, interfaces and generic types. With Visual Studio’s rich autocomplete support for TypeScript it will be a pleasure to write statically typed front-end. Of course we will need to do some work related to transpiling TypeScript to JavaScript, but it will be covered in the part related to Webpack configuration.

TypeScript docs can be found here – we suggest you to do the same thing like with React – please spend some time on reading about it’s features because it will help you understand our examples.


SASS is a CSS preprocessor thanks to which we will be able to use things like variables, imports and mixing in our styling codebase. We may not use all of it’s features from the beginning, but some of them will definitely help us in writing scalable and maintainable styles.


Let’s write some code!

To make sure that you’re ready for starting work on the front-end let’s check if all required packages have been defined in your package.json.

Under dependencies section you should have defined react and react-dom. Under devDependencies you should have at least @types/react, @types/react-dom and typescript:

To install these packages you can click ‘Restore Packages’ on the Dependencies/npm folder in Visual Studio, or you can execute npm install command from the command prompt in the main directory of your project.

Now go to previously created folder for Demo component and create a file Demo.tsx. This extension is a sign that we’re going to use TypeScript along with JSX.

Inside Demo.tsx paste a following code:

Congratulations – you’ve just created your first React component!

Starting from the top you can see that we are importing whole React module – it will be available for us under… React variable. Due to conventions of module resolution in TypeScript we don’t need to provide full path to modules as long as they follow defined convention (basically everything from node_modules folder should work in that way).

Below you can see that we define our component as a class which extends React.Component base class. It’s a generic one, so we need to provide types of two internal objects of every React component called props and state. Props object represents values passed to the component from outside of it, and state is just an internal state of given component.

Another example of passing props and state could look like this:

For now we don’t have to dig into them, so we define them as ‘any’.

When we have our component class defined, we also need to add another very important part of React components – a method called render.

Inside render method we have to return a structure of our component. During every ‘rendering phase’, i.e. after initialization or after changing internal state of it React will call this method to update look of our component.

What about these fancy tags inside render method? This format is called JSX and it has been introduced o make work with components easier. It looks similar to well known HTML, but please be careful because syntax of it is slightly different than syntax of HTML (check it here) – you can express structure of your component with a tree of nodes representing either base elements like h1, or other components already existing in your application. Under the hood each node is being transformed into call of method React.createElement, to which you can pass name of the element, it’s children and some additional parameters. Of course you can stick with JSX but it’s good to know what’s going on there.


Definition of a component presented above is just a recipe – there’s no magic initialization of it or anything like that. Also, React doesn’t initialize all components in our application for us. We need to say explicitly how to initialize them, and where. To do this, we need to define in which ‘environment’ our components should work – in our case it will be Document Object Model (or just DOM). So how to initialize React components in DOM?

It’s worth to know that in React components aren’t coupled with the environment – and it works like that by design. With this approach you can easily create another environment for React components (i.e. as in React Native) without rewriting your base library. Because we’ll be working with DOM, we need to find a way to connect it with React. Package responsible for providing a bridge between React and DOM is called… ReactDOM – you should already have it installed (or at least defined in package.json – ‘react-dom’).

To initialize React on our homepage just for demo purposes let’s go to directory /Frontend/Homepage/ and then create file called index.tsx (on the same level as Components directory, not inside).

In this file paste given fragment of TypeScript code:

ReactDom‘s method render will be responsible for injecting React components into defined parts of our app. It works in a way that we need to provide some base component to render, and – as a second argument – DOM element which will be our root element. We can obtain our root element by using plain DOM API and method called getElementById. Of course now we don’t have any pages with this element, but soon it will be created.

Files like index.tsx will be created for every page where we’d like to work with React. With this approach we’ll have our code splitted, and with going to every page users will need to download only as much of our client-side code as needed.


Few years ago majority of tutorials related to styling websites contained a file called styles.css. It was really a must-have for every single junior web developer. What was the problem with this approach? Of course styles defined in this file were globalIn smaller projects it wasn’t a problem, but with thousands of lines of code it was super hard to keep various rules separated.

Approach to styling a website based on components is slightly different. There will be many files related to styling (.scss in our case), but each of them will be placed as close to given component as possible. Rules inside them will be only related to matching component, along with all assets we’d like to use in the context of components. There will be also files related to external libraries, but they will be bundled (joined) into separate file. For now let’s focus on styling our components.

To see how it works please add a file called Demo.scss in the same directory as Demo.tsx, and inside it add simple css rule related to Demo component (please compare it with a structure of Demo component inside render method):

Now in your Demo.tsx import this file using given syntax:

WAT? Scss file imported from TypeScript file? How does it even work?! And what’s up with this index.tsx file created earlier?

Maybe this configuration looks weird for you, but trust me – this guy in front of us can handle problems like that.

4. Introducing Webpack

Webpack is a module bundler for modern front-end applications. General principle of Webpack is to bundle all dependencies into one (or more) packages starting from entry points defined in config files. High-level overview looks like that (image from Webpack’s main page):

On the left side you can see files created during development phase, and on the right side you can see bundled assets created by Webpack. Webpack will be trying to build our front-end assets during development process by taking a look at our webpack.config.js file, where whole configuration will be placed.

Let’s stop here for a moment and let’s try to list all steps we need to do, to be able to start our application:

  • transpile TypeScript to JavaScript
  • transform JSX syntax into plain old JavaScript
  • convert scss files into plain old css
  • import scss defined in component files and make them work without injecting into cshtml files
  • (nice to have) split various parts of code into bundles dedicated to different parts of our application
  • (nice to have) move shared parts (i.e. React) into common bundles

And guess what – all of this can be achieved with Webpack.

Let’s start our Webpack adventure by creating new file called webpack.config.js on the same level as package.json file.

We start by requiring two modules – path (we’ll be working with paths, that’s not a surprise) and of course webpack (to use some of it’s internals). Below we have defined simple JavaScript object with provided output directory. All bundles created with webpack will be placed there.

And finally, the most important part – config object. It should contain four core parts – a) entry points (for resolving our dependencies and creating bundles), b) output (how to treat newly created bundles), c) loaders (how to transform various dependencies into JavaScript modules and add them to Webpack’s dependency graph), and last but not least – d) plugins (to make additional work related to our modules).

With this knowledge we can update our config file:

Great! Now it’s time for defining some entry points for Webpack. Our entry points will be related to a) separate pages in our app b) common libraries. Each “entry” in entry object will be used to build a separate bundle from discovered (i.e. from import statements) dependencies.

In our example entry will look like this:

Based on that we can see that two bundles will be created – one for homepage, and one for common libraries used across all views in our project. Now the output part:

After creating in-memory bundles Webpack would like to know what to do next. With output section, we basically define where and how to store our bundles. In our case at this moment we have two bundles, so there will be two output files ([name] will be changed to entry name, so there will be homepage.js and libs.js).

Now, time for the loaders (module object in config):

As I said before – loaders are used to transform various types of files (dependencies) into JavaScript modules (because Webpack understands only JavaScript). Thanks to various loaders we can do things like for example importing .scss file into .ts, or bundling our css files with images inside (at the end everything will behave like JS module).

We are working with loaders by defining proper set of file extensions which should be transformed using specific loader (test property), we can exclude some dependencies if they are referenced from some places, and of course we need to define which loaders will be use(d) to build modules.

Our set of rules means that:

  • assets like images will be loaded using url-loader
  • TypeScript files will be loaded using two loaders – first, they will go through awesome-typescript-loader, and then (as a .js files) they will go through babel-loader with React and ES2015 preset applied
  • JavaScript files will be processed using only babel-loader
  • Style (css and scss) files will be loaded using sass-loader and css-loader with a little help from plugin used to extracting styles from .js modules into separate .css files

We need to update our project now to use all of these loaders, because this file is only a recipe for tools we’d like to use. Of course, now we need to provide them into our project.


First, let’s introduce Babel. Babel, as you can read on the homepage of this tool, it’s a JavaScript compiler which will help us to write next-generation JavaScript without thinking too much about compatibility with current browsers. Babel will transform also React JSX files to plain old JavaScript supported with current-generation browsers.

All you need to know now about Babel is the fact that it takes a .js file, looks at config file to see which presets should be applied to this file (how to transform it), and finally it produces compiled result file. Comparing to Webpack, Babel isn’t responsible for module bundling – it’s only role is to compile files, that’s it.

Babel needs one additional file to be included in our project – .babelrc. It should be created at the same directory as webpack.config.js and package.json. It’s content looks like this:

With these presets, babel-loader used in webpack.config.js will be able to transform React / ES2015 files into globally supported version of JavaScript.


We also need to provide ExtractTextPlugin which will handle our scss / css files. To do this, we need to update upper part of our webpack.config.js:

Now the final part – plugins. Plugins config looks like this:

With plugins we are able to do some work with our bundles and modules as a whole, without focusing on single file.

CheckerPlugin is responsible for checking  during build if everything related to our TypeScript code is ok. It should be required first on the top of config file:

ExtractTextPlugin will extract content of modules created by importing scss/css files into separate css files. ProvidePlugin will provide something like ‘global variables’ for other modules bundled by Webpack. CommonChunksPlugin will help us with extracting constantly repeating modules into separate file. SourceMapDevToolPlugin is a useful tool for development stage – with every bundled module there will be added a reference to original source files to allow easier debugging and checking our code in a runtime.

One last thing – to make sure that Webpack will resolve modules with correct extensions properly, we need to add this resolve object on the same level as entry/output/module, etc… :

Phew… a lot of stuff, but we did it!

To be able to use all of these loaders and plugins please update now your package.json file:

…and restore these dependencies (or via npm install from command prompt).

Now it’s time for the first build. From main directory of our project execute command:


If anything went wrong it could mean that you don’t have Webpack installed globally. In this case execute following command:

npm install -g webpack && webpack

Now you should see that building process has been started. After succesful build you should open /wwwroot/dist folder and see if Webpack created files like libs.js, homepage.js, commons.js and some css files. If they are visible and there was no critical errors during build it means that we can finally clean our cshtml views, add references to created bundles and start our app!

5. Wrapping all together

Now, let’s use bundles created by Webpack in our .cshtml files. First, let’s focus on /Views/Home/Index.cshtml – it’s content should look like this:

Here we can see that we’ve created root div element for our Demo component (as it was defined in Index.tsx). There are also two sections – Scripts and Styles to extend our layout with page-specific content (initialization and styles of Demo component).

We also need to update our layout to use these Sections – go to /Views/Shared/_Layout.cshtml and update it’s content:

And that’s it! Now you check if everything works by starting your application in Debug mode (CTRL+F5 in Visual Studio). After few seconds of loading you should see your first component of the homepage of our application. That’s a great progress in terms of our front-end architecture!

Automate your work with Hot Module Replacement

At the end we can do one interesting improvement related to our build process.

We can connect Webpack and ASP.NET app running in Debug mode, and as a result our React components bundled with Webpack will be updated with every change in “tracked” files. What’s even more important – it will happen in real-time, without need for page reloading! To do this, let’s start by adding to our project library called Microsoft.AspNetCore.SpaServices – you can install it via NuGet or via Package Manager Console in Visual Studio by executing command:

Install-Package Microsoft.AspNetCore.SpaServices

Now go to Startup.cs file, and on the upper part of it add given line:

Below you can find Configure method – there you can update middlewares related to working in Development mode:

Nice! Our server-side part has been updated – now let’s do similar work on the front-end. We need three additional packages to be installed as devDependencies. To install them, run:

npm install aspnet-webpack aspnet-webpack-react webpack-hot-middleware –save-dev

Now Webpack will be able to build front-end part of our application during development stage. If you want to enable feature called hot module replacement to do “hot-swap” of our modules, you need to add explicit declaration in some files. For example, you can go to index.tsx and at the end add these lines:

And… it should work now! Try to start your application in Debug mode, change something in your Demo component and wait for automatic reloading of it’s content in front of you! Due to scope of our course we can’t focus more on every single tool we’ll be using, but of course you can read more about HMR related to React components here.

You can also ask where is the configuration part. For now, there’s no configuration (except webpack.config.js). Seriously. A lot of work has been done by guys from ASP.NET Core team, who’ve seen growing potential in SPA / JS apps and started project dedicated for providing connection between ASP.NET Core apps and JavaScript. It’s caled JavaScriptServices, and it’s repository can be found here. There you can find a lot of useful resources related to creating ASP.NET Core back-end for various types of front-ends like these based on React, Angular or Knockout. Full introduction to SPA in the context of ASP.NET Core can be found here.


Oh man! It was a long journey but now our basic front-end setup is done! To sum up, today we:

  • removed bower from our project
  • introduced npm – our one and only package manager for front-end stuff
  • created basic structure for React components
  • created first React component backed by TypeScript
  • created and connected styles with components
  • created basic setup for building our app using Webpack
  • built our app!
  • cleaned up unused parts of our views
  • introduced Hot Module Replacement

A lot of great stuff, but even more is coming! Now, when we have back-end and front-end configured, we can show you how to build features on top of our setup. Stay tuned, because we haven’t finished yet!