webpack wait until bundle finished taking so much time to build - reactjs

I got an issue every time I want to run my react app it takes more than 10 minutes bundle to finished, it stack on these command
[webpack-dev-middleware] wait until bundle finished:
I have tried some solved question on google but it does not solved my problem
it makes me frustrated, any idea? thank you
const merge = require('webpack-merge');
const commonconfig = require('./webpack.common.config.js');
let config = merge(commonconfig, {
devtool: 'source-map',
devServer: {
static: {
directory: __dirname,
publicPath: '/summary/',
},
historyApiFallback: true,
client: {
overlay: false, // There are reference errors coming from de-forms-ui; disable the warning overlay for now
},
},
});
module.exports = config;

Related

React with Webpack not displaying errors

I'm running react with HMR using webpack. When a function is deleted in a server or used shared service is deleted, no errors are emitted, neither in the console nor on the terminal.
This error can not be seen even during the build process.
I've waisted at least a day trying to find a solution for it. Any help is appreciated.
thank you.
const DEV_SERVER = {
contentBase: PATHS.public,
hot: true,
open: true,
hotOnly: true,
historyApiFallback: true,
overlay: true,
port: 3000,
// stats: 'verbose',
// proxy: {
// '/api': 'http://localhost:8888'
// },
More Details
if i have user.service.ts imported in an index.ts file and use in all the other files, then i delete the user.service.ts file.
Expected Behaviour: An error with module not found.
Current Behaviour: Nothing is showing in the console or terminal.
React v 16.13
Webpack v 4.41
Check the source maps used, this worked for me:
devtool: 'cheap-module-source-map'
Did you try the error-overlay-webpack-plugin?
const ErrorOverlayPlugin = require("error-overlay-webpack-plugin");
module.exports = {
plugins: [new ErrorOverlayPlugin()]
);
https://www.npmjs.com/package/error-overlay-webpack-plugin

Best way to integrate webpack builds with ASP.NET Core 3.0?

I'm upgrading my ASP.NET Core app to V3, and using Visual Studio 2019 for development / debugging. The process has been smooth except for this:
public void Configure(…..
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = false,
ReactHotModuleReplacement = false
});
UseWebpackDevMiddleware is no more: https://github.com/aspnet/AspNetCore/issues/12890 .
I'm now looking to understand the best way to have VS run webpack every time I debug, ideally only on JS code that has changed. This was the value I was getting from UseWebpackDevMiddleware. My app is a React app, and it seems like there is some new replacement for this if your app was started from CreateReactApp, but mine was not. (I believe apps that stated from this but then separated are called "ejected.") Is it somehow possible for me to still take advantage of whatever that facility is, even though my app does not leverage CreateReactApp? Also, what is the role of CreateReactApp after it bootstraps your new React application? I imagined it would be only used for inflating template code at the first go.
What is the role of Microsoft.AspNetCore.SpaServices.Extensions in all of this?
I don't need hot module replacement; I don't need server side prerendering. I'm really just trying to understand how to get my JS to transparently build (via Webpack) as part of my debugging process. Is this something that I could hook into MSBuild for? I imagine others are going to face the same question as they upgrade.
Thanks for any suggestions.
So, I was using UseWebpackDevMiddleware for HMR for a much smoother dev process - In the end I reverted to using webpack-dev-server
Steps:
1) Add package to package.json: "webpack-dev-server": "3.8.2",
2) Add webpack.development.js
const merge = require('webpack-merge');
const common = require('./webpack.config.js');
const ExtractCssPlugin = require('mini-css-extract-plugin');
const webpackDevServerPort = 8083;
const proxyTarget = "http://localhost:8492";
module.exports = merge(common(), {
output: {
filename: "[name].js",
publicPath: '/dist/'
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
compress: true,
proxy: {
'*': {
target: proxyTarget
}
},
port: webpackDevServerPort
},
plugins: [
new ExtractCssPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
});
Note that the proxy setting here will be used to proxy through to ASP.Net core for API calls
Modify launchSettings.json to point to webpack-dev-server:
"profiles": {
"VisualStudio: Connect to HotDev proxy": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "http://localhost:8083/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:8492/"
}
}
(also I had some problem with configuring the right locations in webpack, and found this useful
Also, will need to start webpack-dev-server which can be done via a npm script:
"scripts": {
"build:hotdev": "webpack-dev-server --config webpack.development.js --hot --inline",
And then this is bootstrapped
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "build:hotdev");
}
});
(or you can install the npm task runner extension and:
"-vs-binding": {
"ProjectOpened": [
"build:hotdev"
]
}
Alternatively I realise you can proxy the other way using the following - this way any request to under "dist" will be pushed through to the proxy webpack-dev-server
app.UseSpa(spa =>
{
spa.Options.SourcePath = "dist";
if (env.IsDevelopment())
{
// Ensure that you start webpack-dev-server - run "build:hotdev" npm script
// Also if you install the npm task runner extension then the webpack-dev-server script will run when the solution loads
spa.UseProxyToSpaDevelopmentServer("http://localhost:8083");
}
});
And then you don't need to proxy though from that back any more and can just serve /dist/ content
- both hot and vendor-precompiled using as web.config.js like this:
module.exports = merge(common(), {
output: {
filename: "[name].js",
publicPath: '/dist/',
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
compress: true,
port: 8083,
contentBase: path.resolve(__dirname,"wwwroot"),
},
plugins: [
new ExtractCssPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
});
In my opinion, Kram's answer should be marked as accepted as it really gives what's needed. I've spent some time setting up a .NET Core/React/Webpack project recently, and I could not get the spa.UseReactDevelopmentServer to work, but the spa.UseProxyToSpaDevelopmentServer works like a charm. Thanks Kram!
Here are my few gotchas they might help someone:
webpack.config.js (excerpt):
const path = require('path');
const webpack = require('webpack');
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'build.[hash].js',
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/dist',
open: false,
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
DevServer sets its root by publicPath property and completely ignores the output.path property in the root. So even though your output files (for prod) will go to dist folder, under webpack server they will be served under a root by default. If you want to preserve the same url, you have to set publicPath: '/dist'.
This means that your default page will be under http://localhost:8083/dist. I could not figure out a way to place assets under subfolder while keeping index in the root (other than hardcode the path for assets).
You need HotModuleReplacementPlugin in order to watch mode to work and also hot: true setting in the devServer configuration (or pass it as a parameter upon start).
If you (like me) copy some dev server configuration with open: true (default is false), you will finish up with two browsers opened upon application start as another one is opened by the launchSettings "launchBrowser": true. It was a bit of a surprise at the first moment.
Also, you will have to enable CORS for your project otherwise your backend calls will get blocked:
Startup.cs (excerpt):
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "developOrigins",
builder =>
{
builder.WithOrigins("http://localhost:8083");
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseCors("developOrigins");
}
If anything else will come to my mind I will update the answer, hope this helps to someone.
Webpack 5 update
webpack-dev-server command doesn't work anymore. Use:
"build:hotdev": webpack serve --config webpack.config.development.js
You might also need to add target: 'web' to your webpack.config.js in Webpack 5 to enable hot module reload to work:
module.exports = {
target: 'web'
}
Alternatively you might need to create a browserlist file. Hope this issue gets fixed soon.
You mention VS. My solution is good for Visual Studio, but not VS Code.
I use WebPack Task Runner: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebPackTaskRunner
This adds webpack.config.js tasks into the "Task Runner Explorer" in Visual Studio, and you can then bind those tasks to events like "Before Build" or "After Build"
Extension is here : AspNetCore.SpaServices.Extensions
You could find examples here : https://github.com/RimuTec/AspNetCore.SpaServices.Extensions
With core 3.1 or 5.0
React with webpack
using :spaBuilder.UseWebpackDevelopmentServer(npmScriptName: "start");

Make webpack-dev-server to do hot reloading AND eliminate EMPTY response error in React

I have been trying to make React app development easier by using reloading of the app when I modify the files and I tried webpack-dev-server for that (Please, see my previous thread: Can't set up webpack-dev-server to start React app). I made hot reloading working but got an issue: timeouts started to occur on my requests and I see the empty response errors in console. There are threads that discuss the issue, e.g.: https://github.com/webpack/webpack-dev-server/issues/183
but so far I could not make it working. Setting --host 0.0.0.0 is not working, setting --port 3000 eliminates empty response error but hot reloading is gone... Below is my webpack relevant config:
devServer: {
index: '',
open: true,
proxy: {
context: () => true, // endpoints which you want to proxy
target: 'http://localhost:3000' // your main server address
}
},
entry: {
app: ['babel-polyfill', './views/index.js']
//vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './public')
},
devtool: "#eval-source-map",
...
I am starting the app by running npm run dev, here is a part of the package.json:
"scripts": {
"client": "webpack-dev-server --mode development --devtool inline-source-map --port 3000 --content-base public --hot",
"server": "node ./bin/www",
"dev": "concurrently \"npm run server\" \"npm run client\"",
},
So, above if we remove --port 3000 hot reloading on the front end part starts working, but then the timeout is happening. Also, upon modification of the server side code the app is not reloaded unfortunately and I am not sure how to add this feature too. I am using react-hot-loader:
import React from 'react';
import ControlledTabs from './ControlledTabs'
import { hot } from 'react-hot-loader/root'
class App extends React.Component {
render() {
return (
<ControlledTabs/>
);
}
}
module.exports = hot(App);
I think it should be related to the devServer configs most probably and how the webpack-dev-server is started. I just want to find a WORKING way of doing hot reloading instead of falling back into build - run cycle that is annoying and inefficient.
Also, it is really hard to say, what is going wrong, whether --port 3000 is really the issue. I noticed that the webpack-dev-server is somehow working in a very unpredictable way on my project meaning that after doing changes and launching the app I see one result, but then I restart webpack-dev-server and see a different result as if webpack-dev-server is doing something behind the scenes what it wants to and whenever it wants to without notifying me about that.
Update
I changed webpack.config.js to:
watch: true,
devServer: {
index: '',
open: true,
proxy: {
context: () => true, // endpoints which you want to proxy
target: 'http://localhost:3000' // your main server address
}
},
entry: {
app: ['babel-polyfill', './views/index.js']
//vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './public')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
And removed react-hot-loader from the React entry point:
import React from 'react';
import ControlledTabs from './ControlledTabs'
class App extends React.Component {
render() {
return (
<ControlledTabs/>
);
}
}
module.exports = App;
Because otherwise it was giving me a syntax error in console, webpack could not start. After doing that if I modify any react file, whole webpage is reloaded it seems and the net::ERR_EMPTY_RESPONSE remains...
Add a watch to your webpack config.
watch: true
Also, you need to enable module replacement loading within the webpack dev server.
In short, if you see how this config is setup, this is a working example of hot reloading for a very basic react app. It uses ExpressJS as well.
https://github.com/chawk/bare_bones_react/blob/master/webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const express = require('express');
module.exports = {
entry: {
app: './src/index.js'
},
devServer: {
hot: true,
compress: true,
contentBase: path.join(__dirname, 'dist'),
open: 'Chrome',
before(app) {
app.use('/static', express.static(path.resolve(__dirname, 'dist')))
}
},
devtool: 'source-map',
output: {
filename: './js/[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './server/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: [
'.js'
]
}
}

Unable to reload with Express + Webpack Dev Middleware + Webpack Hot Middleware

I've been trying to perform Hot Module Replacement forever with the above setup; with failure. Here's my Webpack Configuration
export default {
entry: [
DEVELOPMENT && "webpack-hot-middleware/client",
PATH.SOURCE
].filter(Boolean),
output: {
path: path.join(PATH.ASSETS, "js"),
publicPath: `http://${getenv("WEB_HOST")}:${getenv("WEB_PORT")}/assets/js`,
filename: DEVELOPMENT ? "bundle.js" : "bundle.[hash].min.js"
},
...
plugins: [
...
DEVELOPMENT && new webpack.HotModuleReplacementPlugin()
...
].filter(Boolean),
...and here's my app.js runnning an express server
const compiler = Webpack(WebpackConfig);
app.use(WebpackDevMiddleware(compiler, {
hot: DEVELOPMENT,
publicPath: WebpackConfig.output.publicPath,
filename: WebpackConfig.output.filename
}));
app.use(WebpackHotMiddleware(compiler));
App/index.jsx
if ( module.hot ) {
import("react-hot-loader").then(({ AppContainer }) => {
module.hot.accept("containers/App", () => {
render(App, AppContainer);
});
});
}
Finally, on file change, HMR updates to browser gives me this on Developer Console.
I've been trying to figure this out forever with little to no luck.
I'm on Webpack 4!
It seems not related to webpack or plugins, have you ever tried replacing "0.0.0.0" with "localhost"? Or use this chrome plugin -- https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Deploying ReactJS app Production

I have finished my ReactJS app and I want to put it in production. I run next command: webpack --progress -p but in chrome F12 I get next error: index.js:1 Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See WebSiteFbReactJs for more details..
It is my webpack.config.js:
'use strict';
const WEBPACK = require('webpack');
const PATH = require('path');
const CopyFiles = require('copy-webpack-plugin');
const BaseName = "/upct";
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
},
context: __dirname,
entry: {
app: ['./src/index.jsx']
},
output: {
path: PATH.join(__dirname, '/public'),
/*path: './public',*/
publicPath: BaseName+'/',
filename: 'index.js'
},
devServer: {
host: 'localhost',
port: 3000,
contentBase: PATH.join(__dirname, '/public'),
inline: true,
historyApiFallback: true,
headers: { "Access-Control-Allow-Origin": "*" }
},
module: {
loaders: [
{
test: /(\.js|.jsx)$/,
loader: 'babel',
query: {
"presets": [
"es2015",
"react",
"stage-0"
],
"plugins": [
"react-html-attrs",
"transform-decorators-legacy",
"transform-class-properties"
]
}
}
]
},
plugins: [
new WEBPACK.DefinePlugin({
BASENAME: JSON.stringify(BaseName)
})
]
}
What could this error be?. It is all OK, right? How could I solve this? Thank you.
EDIT: I am getting next error too: DevTools failed to parse SourceMap: http://MYSERVER.com/upct/src/css/bootstrap.css.map
Please add NODE_ENV = 'production' environmental variable to your Webpack build in order to disable debug information and warnings, most of the property type checks and other developer-friendly tools. It will make the app faster but harder to debug. Use this only when deploying to the production.
In your case, in the plugins section just add:
new WEBPACK.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
Please see documentation about optimizing the production build with React, especially Webpack section.
As for the error with the source maps, it seems that the link is broken and returns 404 Not Found error so Chrome can't fetch the original source code mapping for Bootstrap's CSS. That's not a big issue as you probably won't be looking at it's source but that might be a signal that your Webpack build doesn't deploy source maps when building the app. Please add devtool: 'source-map' to your config file in order to produce source maps which will improve the debugging experience on production by translating bundled code to original source files.
UglifyJs will minimize the code size by renaming variables, function names and by other optimization tricks. You can add it to your plugins section of the config file the same way:
new WEBPACK.optimize.UglifyJsPlugin({
compress: {
// suppresses warnings, usually from module minification
warnings: false,
},
}),
There are many possible optimizations, for more information please see this optimization guide.

Resources