# Initial page

Based off <http://blog.wecodeyoursite.com/how-to-setup-asp-net-mvc-reactjs-typescript-webpack/>

All packages and dependencies that are required for our React project are tracked in package.json. Therefore, before starting off, we need to create package.json file in the application root folder, using the following npm command.&#x20;

```bash
npm init -y
```

Once package.json has been created, include this file in your ASP.NET solution. Open the file and fill in any blanks to prevent warning errors when installing subsequent packages. You may also need to add in the repository property as below:

```scheme
{
  "name": "Your Project Name",
  "version": "1.0.0",
  "description": "Packages for your project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "https://github.com/...."
  }
}

```

Now install react and react-dom followed by the rest of the below packages

```bash
npm i --save-dev react react-dom 
npm i --save-dev webpack webpack-cli
npm i --save-dev typescript
npm i --save-dev ts-loader
```

The first npm command will create the **node\_modules** folder and also install the latest react and react-dom package.

Apart from the react packages we have also installed webpack, typescript and ts-loader.&#x20;

The typescript package lets us write our code in typescript which is lot easier and cleaner. However, browsers don't understand typescript and therefore we need a package like ts-loader to transpile our typescript into javascript.&#x20;

With all the javascript that is generated across so many files and packages, there is a lot of code that needs to be downloaded which can impact performance over the web. In order to optimise performance we then use a tool like Webpack to bundle all our js code in to one minified file.&#x20;

## Configure Webpack for ASP.NET MVC

For Webpack to run with ASP.NET MVC we need to setup **webpack.config.js**. If you don't see it in in the **Add | New Item** menu, you will need to install the VS extension **webpack task runner.**&#x20;

Once you add webpack.config.js to your project, make the following updates to the project too:

1. Decide the source folder for your React files. You can stick to the default naming convention and create a folder called **src** or choose any other name. Include this folder in your project.
2. Create **index.tsx** in this folder. This will be the entry point in to our app.
3. Update **webpack.config.js** by changing the "entry" property to the above file
4. Also change the "output" property to "./reactApp.js". &#x20;
5. We will also be setting the mode to development for now and watch : true in our config. This will keep track of all the changes made to the .js files and bundle them automatically
6. Remove the devserver section and add source map settings devtool: ‘source-map’. This will keep track of source maps while bundling our .js files and also help with debugging code with our browser devTools.&#x20;
7. In the module section, remove the existing "loaders" property which uses babel and change to ts-loader and exclude "node\_modules'"

The final webpack.config.js will look as below:

{% code title="./webpack.config.js" %}

```javascript
"use strict";

module.exports = {
    mode: "development",
    watch: true,
    entry: "./src/index.tsx",
    output: {
        filename: "./reactApp.js"
    },
    devtool: "source-map",
    resolve: {
        extensions: ['.ts', '.tsx', '.js']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
        ]
    }
};
```

{% endcode %}

## More updates

For us to start using typescript, we also need to add tsconfig.json file in our project. Once added, add the below options to it.

{% code title="./tsconfig.json" %}

```javascript
{
  "compilerOptions": {
    "moduleResolution": "Node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "module": "CommonJS",
    "target": "ES6",
    "jsx": "react"
  },
  "exclude": [
    "**/bin",
    "**/bower_components",
    "**/jspm_packages",
    "**/node_modules",
    "**/obj",
    "**/platforms",
    "wwwroot"
  ]
}
```

{% endcode %}

Next add the "tsc"  and "start" entries to the scripts section in package.json

{% code title="./package.json" %}

```javascript
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "./node_modules/typescript/bin/tsc",
    "start": "webpack --config webpack.config.js"
  }
```

{% endcode %}

This config setting will allow us to compile our code using either nodejs or webpack task runner. The start command will now build our typescript files and then webpack will bundle it. Although we can use npm commands to compile our typescript code, for now but we will do it through the Visual Studio task runner.

## Finally... we build

In Visual Studio, select View  |   Other Windows  |  Task Runner Explorer  |  Run - Run Development.  If everything has been configured properly so far, you should see the below output in Task Runner Explorer.&#x20;

```bash
cmd /c SET NODE_ENV=development&& webpack --color
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
asset ./dist/reactApp.js 211 bytes [emitted] (name: main)
./src/index.tsx 1 bytes [built] [code generated]
webpack 5.9.0 compiled successfully in 3874 ms
[webpack-cli] watching files for updates...
[webpack-cli] Compilation starting...
[webpack-cli] Compilation finished
assets by status 211 bytes [cached] 1 asset
cached modules 1 bytes [cached] 1 module
webpack 5.9.0 compiled successfully in 141 ms
[webpack-cli] watching files for updates...
```

Once the above is done, you will notice a new "dist" folder with the file reactAppp.js with in it.

## Hello React

We can now add code to our MVC View files and index.tsx and check out the output.&#x20;

But before we begin, we need to add a scripts tag to our Layout file in ASP.NET MVC. Add this tag as far below as possible to avoid javascript errors. If you have multiple Layout files, you can add it in the topmost root  Layout file.

{% code title="\_Layout.cshtml" %}

```aspnet
<script src='~/dist/reactApp.js'></script>
```

{% endcode %}

In the view file you wish to add the React component, add the following line. In the demo, the file is Index.cshtml

{% code title="Index.cshtml" %}

```aspnet
<div id="app"></div>
```

{% endcode %}

In Index.tsx add the below.

{% code title="./src/index.tsx" %}

```jsx
import * as React from 'react';
import * as ReactDom from 'react-dom';

ReactDom.render(<h1>Hello React!</h1>, document.getElementById("app"));
```

{% endcode %}

Users familiar with React will recognise the above. The React scripts will find the HTML element with the Id "app" and replace this with our React component - in this case the H1 Hello React tag.

Run and done!
