ASP.Net核心:在VS2017中设置React.js + webpack + babel

时间:2017-08-01 14:46:17

标签: c# reactjs webpack asp.net-core

在使用ReactJS(在webpack-server上运行)之后,决定在Visual Studio 2017中尝试ASP.Net Core项目。

  1. 我创建了空ASP.Net Core项目。
  2. 删除了所有内容     wwwroot以及与bower相关的内容。
  3. 删除了所有控制器     除Home以外的其他视图除外Home/Index.cshtml
  4. 加     webpack.config.jspackage.json.babelrc
  5. Asp.React
  6. 安装Nuget

    我的package

    {
      "name": "TrainDiary",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "css-loader": "^0.28.4",
        "react": "^15.6.1",
        "react-dom": "^15.6.1",
        "style-loader": "^0.18.2"
      },
      "devDependencies": {
        "babel-core": "^6.25.0",
        "babel-loader": "^7.1.1",
        "babel-preset-react": "^6.24.1",
        "css-loader": "^0.28.4",
        "html-webpack-plugin": "^2.29.0",
        "clean-webpack-plugin": "^0.1.16",
        "style-loader": "^0.18.2",
        "webpack": "^3.4.1",
        "webpack-dev-server": "^2.6.1"
      },
      "-vs-binding": {
        "BeforeBuild": [
          "build"
        ]
      }
    }
    

    我的webpack config

    var CleanWebpackPlugin = require('clean-webpack-plugin');
    let path = require('path');
    const bundleFolder = "wwwroot/build/";
    var HTMLWebpackPlugin = require('html-webpack-plugin');
    
    var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
            template:  path.resolve(__dirname,  'Scripts/app/index.html'),
            filename: 'index.html',
            inject: 'body'
    });
    
    module.exports = {
        entry: path.resolve(__dirname, 'Scripts/app/Core/app.js'), 
        module:{
            loaders:[
                {
                    test: /\.js$/,
                    exclude: [/node_modules/],
                    loader: 'babel-loader'
                },
                {
                    test: /\.css$/,
                    loader: "style-loader!css-loader"
                }
            ]
        },
        output:{
            filename: 'index.js',
            path:  path.resolve(__dirname, bundleFolder)
        },
        stats: {
                colors: true,
                modules: true,
                reasons: true,
                errorDetails: true
        },
        plugins: [ new CleanWebpackPlugin([bundleFolder]), HTMLWebpackPluginConfig]     
    };
    

    babelrc很简单,就像{ presets:['react'] }

    一样

    因此,当我运行npm run build时一切正常,wwwroot它也会生成index.jsindex.html

    但是当我运行我的应用程序时没有任何反应!我的意思是什么都没有。空白的白页。控制台没有错误。就像那样。

    另外,这是我的Startup.cs

    namespace TrainDiary.Web
    {
        using React.AspNet;
        using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.DependencyInjection;
        using Microsoft.Extensions.Logging;
        using Microsoft.AspNetCore.Http;
        public class Startup
        {
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
                Configuration = builder.Build();
            }
    
            public IConfigurationRoot Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                // Add framework services.
                services.AddMvc();
                services.AddLogging();
                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
                services.AddReact();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseReact(config =>
                { });
                app.UseStaticFiles();
                app.UseDefaultFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
            }
        }
    }
    

    HomeController

      public class HomeController : Controller
        {
            public IActionResult Index()
            {
                return View();
            }
    }
    

    Home/Index.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello world</title>
    </head>
    <body>
        <!-- Load all required scripts (React + the site's scripts) -->
        @Html.Partial("~/wwwroot/build/index.html")
    </body>
    </html>
    

    为什么?这种方法有什么问题?

    UPD

    入口点index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './app/Core/app.js'
    
    ReactDOM.render(
      <App />,
      document.getElementById("content")
    );
    

    Core/app.js就在这里

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    export default class App extends React.Component {
        render() {
            return (
               <div>
                   Hello, React!
               </div>
           )
        }
    }
    
    我们尝试在index.html

    中呈现的

    Index.cshtml

    <body>
        <div id='content'></div>
    </body>
    

    渲染内容的截图:

    enter image description here

    UPD2

    正如何建议的那样 - 改变了Index.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello world</title>
        <script src="~/build/index.js"></script>
    </head>
    <body>
        <!-- Load all required scripts (React + the site's scripts) -->
    
        <div id='content'></div>
    </body>
    </html>
    

    并删除webpack-html-plugin

    这就是我现在得到的(css-loader工作顺便说一下):

    enter image description here

    UPD3

    修复了webpack.config(入口点)中的一些错误内容,但仍然没有成功:

    var CleanWebpackPlugin = require('clean-webpack-plugin');
    let path = require('path');
    const bundleFolder = "wwwroot/build/";
    
    
    module.exports = {
        entry:'./Scripts/index.js', 
        module:{
            loaders:[
                {
                    test: /\.js$/,
                    exclude: [/node_modules/],
                    loader: 'babel-loader'
                },
                {
                    test: /\.css$/,
                    loader: "style-loader!css-loader"
                }
            ]
        },
        output:{
            filename: 'index.js',
            path:  path.resolve(__dirname, bundleFolder)
        },
        stats: {
                colors: true,
                modules: true,
                reasons: true,
                errorDetails: true
        },
        plugins: [ new CleanWebpackPlugin([bundleFolder])]     
    };
    

    UPD4

    现在它有效!在之前的例子中,我没有注意到调试器控制台的错误,如here所述。

    所以我改变了Index.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hello world</title>
    </head>
    <body>
        <!-- Load all required scripts (React + the site's scripts) -->
        <div id='content'></div>
        <script src="~/build/index.js"></script>
    </body>
    </html>
    

    现在好了!

    enter image description here

1 个答案:

答案 0 :(得分:1)

意见摘要:

  • 确保您的应用代码正在呈现

  • 删除HTMLWebpackPlugin并更改Index.cshtml以包含bundle.js(mvc视图中的局部视图使用html wepack插件加载完整模板)

很高兴为您提供帮助!