After some playing around with ReactJS
(which was running on webpack-server
), decided to try ASP.Net Core
project in Visual Studio 2017.
- I created empty
ASP.Net Core
project. - Removed all stuff in
wwwroot
and stuff related tobower
. - Removed all controllers
except
Home
and removed views exceptHome/Index.cshtml
- Added
webpack.config.js
,package.json
and.babelrc
- Installed
Asp.React
fromNuget
My 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"
]
}
}
My 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
is simple like that { presets:['react'] }
So, when I run npm run build
everything is fine, in wwwroot
it generates index.js
and index.html
as well.
But nothing happens when I run my application! I mean nothing at all. Blank white page. No error in console. Just like that.
Also, here is my 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>
How come? What's wrong with this approach?
UPD:
entrance point 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
is here
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends React.Component {
render() {
return (
<div>
Hello, React!
</div>
)
}
}
index.html
which we try to render in Index.cshtml
<body>
<div id='content'></div>
</body>
Screenshot of the rendered stuff:
UPD2:
As Jose advised - changed Index.cshtml
like that:
<!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>
and removed webpack-html-plugin
.
Thats what I got now (css-loader
worked btw):
UPD3:
Fixed some wrong stuff in webpack.config
(entry point), but still no success:
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:
Now it works! In previous case I just didn't pay attention to debugger console with error like described here.
So I changed Index.cshtml
like that:
<!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>
And now it's fine!