asp.net core 2.1 Webpack 4 React not starting correctly

佐手、 提交于 2019-12-10 09:34:00

问题


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

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"
    ],    
}

回答1:


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 .




回答2:


The create-react-app server did not start listening for requests within the timeout period of 50 seconds

that happened to me only on startup so I added spa.Options.StartupTimeout:

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

                if (env.IsDevelopment())
                {
                    spa.Options.StartupTimeout = TimeSpan.FromSeconds(120);
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });



回答3:


As hinted at by the error message, the React development server middleware for Asp.NET Core is tied to create-react-app. It will not work when invoking the Webpack dev server directly. It scans the output of the script for the text "Starting the development server" which is specific to create-react-app.

You can get around it by setting the start command in package.json as follows:

"start": "echo Starting the development server && node node_modules/webpack-dev-server/bin/webpack-dev-server.js --port %PORT% --mode development"

This makes Asp.Net Core middleware happy and it also makes the dev server listen on the right port.

Alternatively, you can try convert your setup to get rid of the full Webpack setup and use create-react-app.

Please note that there seems to be an issue in the answer provided by itminus. The second section, launching without react-scripts, cannot work because the create-react-app "Starting the development server" will not be there.



来源:https://stackoverflow.com/questions/52386839/asp-net-core-2-1-webpack-4-react-not-starting-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!