DEV Community

JEFF
JEFF

Posted on

5 1

How to load react.js apps into existing ASP.NET , Simple AF 🥵

In this post, I will show how to easily load react apps into existing ASP.NET applications, let it be js, jsx , tsx no barrier.

Note: I've used ASP.NET Web Forms.

Step 1:-

Take an existing react.js project or create a new one and keep it ready .

Step 2:-

Go to View > Terminal to open the command line and enter these commands to install your project's packages and webpack:

cd <ProjectName>
npm install webpack webpack-cli

Step 3:-

Create a filename webpack.config.js in the root dir , and paste the following code.



const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const glob = require("glob");

module.exports = {
  entry: {
    "bundle.js": [
      ...glob.sync("build/static/?(js|css)/main.*.?(js|css)").map(f => path.resolve(__dirname, f))
    ],
  },
  output: {
    filename: "build/static/js/bundle.min.js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jpg|gif|svg)$/i,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 8192,
              name: "static/media/[name].[hash:8].[ext]",
            },
          },
        ],
      },

      {
        test: /\.(png|jpg|gif|svg)$/i,
        include: path.resolve(__dirname, "media"),
        use: [
          {
            loader: "file-loader",
            options: {
              name: "static/media/[name].[hash:8].[ext]",
            },
          },
        ],
      },
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()],
  },
};



Enter fullscreen mode Exit fullscreen mode

save it and

install the following dependencies
CSS loader:
npm install css-loader style-loader mini-css-extract-plugin
URL loader:
npm install url-loader
SVG loader:
npm install @svgr/webpack
Install process to avoid the "process is not defined" error:
npm install process

save it.

Step 4

Now come back to the root directory in cmd and build the react app.

npm run build

As we have already declared the build script in webpack.config.js file , we will get the build folder added with the bundled folder inside the dist > build >static> js.

for a succesfull build , here is the log

log file

we can set the entry and output in the webpack.config file .

entry and output

we can customize the output bundle file name and the folder.

Step 5

According to the path we set , we should have got a folder name dist created , inside which you can find build/static/js/bundle.min.js .

just copy the bundle file from there and add the bundle file inside the ASP.NET Project's root folder , its a best practice to create a folder and put that bundle file inisde the folder .

Step 6

After placing the bundle file , now create a new .aspx page and paste the script like this .



<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="TestReactWebApp.About" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div id="root"></div>
  <script src="Scripts/dist/build/static/js/bundle.min.js"></script>

</asp:Content>




Enter fullscreen mode Exit fullscreen mode

Here I have my own folder structure inside the script tag , but You can change the folder structure according to your wish.

** Note that inside the .aspx page you can see the div tag with id root . inside the index.js of our react project , I have mentioned the getElementById as "root" **



import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();



Enter fullscreen mode Exit fullscreen mode

Step 6
Build the asp project and run the server .

if you find the images are not loaded . hover over the images in the browser and using the developer tools and , try to locate the path , then add the exact path as folders in the root directory. Inside the folder , add the .svg file form the build/static/media folder in your react project and paste it.

This is how you can add the react project inside the ASP project easily . Feel free to ask any doubts , or if you find any issues , let me know , I will try my best to give solutions for you.

Top comments (3)

Collapse
 
ofofon profile image
Ofofonono Umoren •

Hi, thanks for sharing Jeff.
Please can you reply with the url to the repository for the code. Would be great to see your package.json as I cannot get the webpack --config webpack.config.js script to run

Collapse
 
noob_jeffrey profile image
JEFF •

Will share asap .

Collapse
 
noob_jeffrey profile image
JEFF •

{
"name": "test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.10.6",
"@mui/icons-material": "^5.15.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.14",
"@types/node-sass": "^4.11.3",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@types/react-router-dom": "^5.3.3",
"@types/react-slick": "^0.23.10",
"axios": "^1.3.6",
"buffer": "^6.0.3",
"crypto-js": "^4.2.0",
"date-fns": "^3.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-scripts": "5.0.1",
"sass": "^1.69.7",
"slick-carousel": "^1.8.1",
"typescript": "^4.9.5",
"validator": "^13.9.0",
"web-vitals": "^2.1.4",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"xlsx": "^0.18.5"
},
"scripts": {
"start": "react-scripts start",
"build": "npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/react-helmet": "^6.1.6",
"react-router-dom": "^6.8.0"
}
}

this is my pacakge.json , plz ignore my dependencies and focus on scripts .

this is my webpack.config.js

const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");
const glob = require("glob");

module.exports = {
entry: {
"bundle.js": [
...glob
.sync("build/static/?(js|css)/main.*.?(js|css)")
.map((f) => path.resolve(__dirname, f)),
],
},
output: {
filename: "build/static/js/bundle.min.js",
},
module: {
rules: [
{
test: /.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /.(png|jpg|gif|svg)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
name: "static/media/[name].[hash:8].[ext]",
},
},
],
},

  {
    test: /\.(png|jpg|gif|svg)$/i,
    include: path.resolve(__dirname, "media"),
    use: [
      {
        loader: "file-loader",
        options: {
          name: "static/media/[name].[hash:8].[ext]",
        },
      },
    ],
  },
],
Enter fullscreen mode Exit fullscreen mode

},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
};

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!