Jake Kruse
Jake Kruse

Reputation: 61

Configure React Dev Server within an ASP.NET Core Application

I have an existing ASP.NET Core application (that uses razor pages) and I am trying to convert it, one component at a time, to React until I can completely make it a SPA. The idea is to create an entry point for each of my razor pages until I can combine them all into one SPA. I have most of this working except for the use of webpack-dev-server to serve my bundles. The problem I am having is the ASP.NET app runs on port 44321 and the dev server runs on port 8080 so the script tags in my .cshtml files cannot see the bundles that are being hosted from webpack.

I can temporarily change them from:

<script src="./dist/[name].bundle.js"></script>

To something like:

<script src="http://localhost:8080/[name].bundle.js"></script>

To get around this, but this is not long term solution.

I have created a sample application to showcase what I am trying to accomplish here: https://github.com/jkruse24/AspNetReact.

Is there any way to either get my ASP.Net application to listen on the port that webpack-dev-server is serving to (without changing my script tags) or to have my webpack-dev-server serve to the port that my ASP.Net app is running on?

I have tried to use the .NET CORE SPA middleware (Microsoft.AspNetCore.SpaProxy) but either I have not configured it correctly or I am misunderstanding what it is used for. Upon adding in the below code (which is commented out in my github sample) my application still looks at the .\dist directory for my bundles (which are still there from running actual builds).

    if (env.IsDevelopment())
    {
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "./ClientApp";
            spa.UseReactDevelopmentServer(npmScript: "start");
            spa.UseProxyToSpaDevelopmentServer("http://localhost:8080");
        });
    }

Upvotes: 4

Views: 1387

Answers (1)

Jake Kruse
Jake Kruse

Reputation: 61

I ended up getting this working using the .NET Core SPA Middleware. When I originally tried to used the middleware, it was working fine, but I didn't have my webpack dev server configured to serve my bundles to the correct location.

As you can see above, I was serving them to

http://localhost:8080/[name].bundle.js

when they needed to be served to

http://localhost:8080/dist/[name].bundle.js

My problem was that my webpack publicPath was not set correctly. I made an update commit on my repository here. More specifically, this was the file diff that solved my problem.

Upvotes: 2

Related Questions