Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core 2.1 Webpack 4 React not starting correctly

Can not figure out, why when I am simply running npm run start from command line, project starts up and everything seems to be working fine.. But If I am trying to start it on IIS from Visual studio it starts browser window (which gets timed out "The create-react-app server did not start listening for requests within the timeout period of 50 seconds"). And after few seconds it starts a second browser tab, on new port, which loads my project as desired..

I very believe there is problem with my StartUp.cs, just cant figure out, where and why..

If needed I can provide any additional needed information.

My project structure:

 web
    |
    bin-
    ClientApp
        |
        dist-
        node_modules-
        public- index.html
        src - index.tsx
        package.json
        tsconfig.json
        tslint.json
        webpack.config.js
    Controllers-
    obj
    Pages
    Properties
    appsettings.Development.json
    appsettings.json
    Program.cs
    Startup.cs

Additionaly screen shot, of exact structure enter image description here

webpack.config.js

 const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "[name].bundle.js",
        path: __dirname + '/dist',
    },
    devtool: 'source-map',
    resolve: {
        extensions: ['.js', '.json', '.ts', '.tsx'],
    },
    module: {
        rules: [{
                test: /\.(ts|tsx)$/,
                loader: 'awesome-typescript-loader',
            },
            {
                test: /\.html$/,
                use: [{
                    loader: "html-loader",
                    options: {
                        minimize: true
                    }
                }]
            },
            {
                test: /\.css$/,
                use: [{
                    loader: 'style-loader',
                }, {
                    loader: 'css-loader',
                }, ],
            },
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: "./public/index.html",
            filename: "./index.html"
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        })
    ]
};

package.json

{
  "name": "ClientApp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.1.0",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-react": "^7.0.0",
    "awesome-typescript-loader": "^5.2.1",
    "babel-loader": "^8.0.2",
    "css-loader": "^1.0.0",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "install": "^0.12.1",
    "mini-css-extract-plugin": "^0.4.2",
    "react": "^16.5.1",
    "react-dom": "^16.5.1",
    "style-loader": "^0.23.0",
    "tslint": "^5.11.0",
    "typescript": "^3.0.3",
    "webpack": "^4.19.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.8"
  },
  "dependencies": {
    "@types/react": "^16.4.14",
    "@types/react-dom": "^16.0.7"
  }
}

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

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

tsconfig.json

{
    "compilerOptions": {
        "noImplicitAny": true,
        "sourceMap": true,
        "target": "es6",
        "jsx": "react",
        "moduleResolution":"node",
        "allowSyntheticDefaultImports": true,
        "module": "ESNext",
    },
    "exclude": [
        "node_modules"
    ],    
}
like image 818
DevyDev Avatar asked Dec 14 '22 14:12

DevyDev


1 Answers

I create a new react template using your configure above and find out that when the command npm run build fails or npm start fails , or when the AspNetCore cannot find the correct URL to the Webpack Dev Server , it will complain the same error as you described :

which gets timed out "The create-react-app server did not start listening for requests within the timeout period of 50 seconds"

Quick fix

As the error describes , it seems that there's something wrong with the react-scripts . However , when I look into the package.json file, I find there's no create-react-app dependencies configured at all .

So I add a react-scripts dependencies by npm i react-scripts --save-dev

    "react-scripts": "^1.1.5",

and replace your npm start and build with :

"scripts": {
    "start": "rimraf ./build && react-scripts start",
    "build": "react-scripts build"
},

Now it works fine when launched in Visual Studio .

Launching without react-scripts

Since you said it worked fine by npm start. I guess the reason is the ASP.NET Core cannot find the correct URL served on Webpack dev server .

So I create another new react project with your package.json :

"scripts": {
    "start": "webpack-dev-server --port 3000 --mode development --open",
    "build": "webpack --mode production"
},

As the default dev server listens on Port 3000, and the contentBase is /public , so I add a configuration in your webpack.config.js:

devServer: {
    contentBase: __dirname + "/public/",
    inline: true,
    port: 3000,
},

I notice that you have dependencies on babel , so I add a .babelrc config and a dependency on @babel/plugin-proposal-class-properties :

{
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties",
          {
            "loose": true
          }
        ]
    ],
    "presets":["@babel/env","@babel/react"]
}

Also , I don't know whether you have files of jsx or not , so I just add a rule on webpack.config.js:

{
    test:/\.jsx?/,
    loaders:['babel-loader']
},

Because I have already got a index.html (generated by template) , I remove the HtmlWebPackPlugin configuration :

plugins: [
    // new HtmlWebPackPlugin({
    //     // template: "public/index.html",
    //     // // filename: "index.html"
    // }),
    new MiniCssExtractPlugin({
        filename: "[name].css",
        chunkFilename: "[id].css"
    })
]

When I test the default react template (havingthe default package.json replaced with yours ) , it works fine now .

like image 195
itminus Avatar answered Jan 22 '23 11:01

itminus