0

I am struggling to revamp my .NET Core application and not sure which way I need to proceed. This is an older website that was originally built using Asp.NET and Razor pages and now I am trying to speed it up and update the UI to conform to new libraries and methods (React, Angular etc.).

Since reprogramming the entire UI is not within the time allowed it seemed that React would be a good fit. So I created a new React application using

create-react-app client-app --scripts-version=react-scripts-ts

under an MVC area folder (each area will have to have its own app) and I can serve and build the client via Power Shell and everything works great.

The problem I have is moving the output directory of the generated scripts to the wwwroot folder. I need to be able to load the scripts from the wwwroot since I can't use SPA Services due to routing, filters and other issues with the existing project.

This is my first attempt using React so I figured it would be easy to change the output of the files but I can't seem to be able to figure out how.

I updated tsconfig.json to change the output directory using

"outDir": "../../../wwwroot/areas",

And this doesn't seem to do a thing, the only way I have been able to get any results is by ejecting the React project using npm run eject and I get a bunch of files including the webpack.config.prod.ts and webpack.config.dev.ts files. When I did this I noticed that the directory is coded in the wepack.config.ts.

After looking online for an answer I noticed that some articles recommend using the webpack-cli instead of npm and specifying a configuration file. But when I do this I get a variety of errors saying the config file is not in the root directory so I tried moving it into the ./src directory then I got another error that the entry module couldn't be found because it couldn't resolve the ./src directory but I can't find where it is referencing src from.

Most of the information I can find on this is either obsolete or plain doesn't work. Even the Typescript.org site is still referencing .NET Core 1.X.

I did find this ReactJS.NET but doesn't look like it is very current and the example they have wouldn't load, gave a ton of errors.

Is there an easy way to configure React for this website or am I forced to fall back on old libraries like AngularJS or KnockOut? Can React be set up to be served like this and compliment the UI allowing me to still use the Razor pages?

1 Answer 1

1

I was able to get this setup the way I needed to, including Webpack hot-module replacement.

In order to get control over the configuration that is needed I needed to eject the react-client-app by running:

`npm run eject`

This will create a few directories and files under your app root, these contain the webpack configurations for both production and debugging.

For my project I didn't want the static/ folders, in order to change the output of the files, there are several areas in the webpack.config that controls these for example:

webpack.config.js

output: {
  ...
  filename: 'js/[name].js',
  chunkFilename: 'js/[name].chunk.js',
  ...
},

....

// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
   test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
   loader: require.resolve('url-loader'),
   options: {
      limit: 10000,
      name: 'media/[name].[ext]',
   },
},

...

For some reason, the default React TS template (create-react-app <name> --typescript) doesn't reference tsconfig.json. One of the Keys to get this going was to install tsconfig-paths-webpack-plugin. This uses the paths defined in the tsconfig.json to resolve alias's and paths, this enables you to include modules from custom paths instead of using relative paths like:

import <name> from 'core/common/<name>';

The next item of business was to add a homepage entry in the package.json:

{
   "name": "<AppName>",
   "homepage": "/<AreaName>",
   "version": "0.1.0",
   ...
}

This will append the homepage value to the paths and point it to the right area. I was originally thinking that I had to manually build the client instead of using Javascript Services (Spa) but this is not the case. Using Spa for different areas really keeps things nice and neat, there is no reason to output to the wwwroot folder since SpaStaticFiles can be set to any root and path. The next step was to update the Startup.cs to add Javascript Services.

Startup.cs

  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
     // In production, the Angular files will be served from this directory
     services.AddSpaStaticFiles(configuration =>
     {
        // Adds the path to the React files
        configuration.RootPath = "Areas/<AreaName>/ClientApp/build";
     });

     return services.ConfigureApplicationServices(Configuration);
  }

  application.UseSpaStaticFiles(new StaticFileOptions
  {
     // This is the key to getting things working, this is the path of the Area
     RequestPath = "/<AreaName>",
  });

  application.UseSpa(spa =>
  {
     spa.Options.SourcePath = "Areas/<AreaName>/ClientApp";

     if ( env.IsDevelopment() )
     {
        spa.UseReactDevelopmentServer(npmScript: "start");
     }
  });

The React app is now served from the Area. There is no need to copy files to the wwwroot since Javascript Servies takes care of this, just reference any files as they were in root, the homepage value will be prepended to the path.

Finally to load the application I initiated the application through a standard Controller/View and used the compiled index.html to grab the required imports to return.

View

@{
   Layout = null;
}
<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8" />
   <link rel="shortcut icon" href="/<AreaName>/favicon.ico" />
   <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
   <meta name="theme-color" content="#000000" />
   <link rel="manifest" href="/<AreaName>/manifest.json" />
   <title>React App</title>

   <!-- Webpack Styles -->
   <link href="/<AreaName>/css/vendors~main.chunk.css" rel="stylesheet">
   <link href="/<AreaName>/css/main.css" rel="stylesheet">
</head>
<body>
   <noscript>You need to enable JavaScript to run this app.</noscript>

   <div id="root"></div>

   <!-- Webpack Scripts -->
   <script src="/<AreaName>/js/vendors~main.chunk.js"></script>
   <script src="/<AreaName>/js/main.js"></script>
</body>
</html>

In order to get react-router-dom to function properly with MVC and its routes you need to use the HashRouter instead of BrowserRouter.

Note: If you use npm run build before launching a development session the production built files will be used not the debug compiled files. This will cause some confusion as nothing will update. To get everything to update when a change is made just remove the ./build directory and launch again.

I hope I included everything if not just post a comment I and will add what I missed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.