Is it possible to move webpack-dev-server default context - reactjs

If I start my webpack-dev-server it listens for my application on localhost:8080/. I want now move the context for application from '/' to '/test'. Is there any way to do this?
Every help is welcome.
My part of package.json to start webpack-dev-server
"devserver": "./node_modules/.bin/webpack-dev-server --host 0.0.0.0 --inline --hot --config webpack.config.devel.js --content-base public/"

It seems to work with webpack config. Tho original configuration looks like
...
module.exports = {
devtool: 'source-map',
entry: [
'./src/index.tsx'
],
output: {
path: path.join(__dirname, 'public/dist'),
filename: 'my_app.js',
publicPath: '/dist'
},
...
After change the publicPath attrib the application is accessible with context '/test'
output: {
path: path.join(__dirname, 'public/test'),
filename: 'my_app.js',
publicPath: '/test/'
},

Related

Dockerizing react app with webpack, connection issues

I'm lately trying to dockerize my react app to learn docker.
I'm using weback for managing this project.
Now here is the thing, after I run dev script npm run dev, server gets on, but I'm not able to connect to it either on host (posting container on 3000:3000) and inside container for any-given ports that came up to my mind (like 8000, 8080, 3000, 5000). It just seems to me like the port connection is not set up properly.
Reading some webpack docs did not give me any clue.
The questions are: best way to define server scripts to run ?
My way of doing it is:
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
Is there any default-like port that webpack sets its connection to (maybe a way to change it)?
What I did establish, is that for 90% it's my webpack config. After dockerizing react app with create-react-app I did have successfull start.
My webpack.config.js :
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: { index: path.resolve(__dirname, "src", "index.js") }, //"./src/index.js",
output: {
path: path.resolve(__dirname, "./static/frontend"),
filename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
optimization: {
minimize: true,
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production"),
},
}),
],
};

Webpack bundle.js changes not showing in a Spring application without restarting the server?

I followed this tutorial for creating a Spring-boot+ ReactJs app: https://spring.io/guides/tutorials/react-and-spring-data-rest/
The application starts fine with ./mvnw spring-boot: run, and I have an NPM script "watch": "webpack --watch -d" that runs the following configuration
var path = require('path');
module.exports = {
entry: './src/main/js/app.js',
devtool: 'sourcemaps',
cache: true,
mode: 'development',
output: {
path: __dirname,
filename: './src/main/resources/static/built/bundle.js'
},
module: {
rules: [
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
use: [{
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}]
}
]
}
};
app.js gets compiled into bundle.js as expected but if I don't restart the server with ./mvnw spring-boot:run when I refresh the page I can't see the changes.
I might be missing something, is maybe spring-boot not using my bundle.js file but a copy of some sort?
I can guess embedded tomcat does not hot reload static files. You can try some of these Refreshing static content with Spring MVC and Boot
But will also share my solution, which is using webpack-dev-server to hot reload and web development in general.
const path = require('path');
...
devServer: {
contentBase: path.join(__dirname, 'src'),
publicPath: '/build',
port: 8000,
proxy: {
"**": "http://localhost:8080"
}
},
and then run webpack-dev-server command to run it. It compiles you app on the fly and your changes are reflected immediately, definitely give it a try.
I got the same question and solve it today.
The key is to run npm run watch and mvn spring-boot:run at the same time.
make sure you have
"scripts": {
"watch": "webpack --watch -d --output .//classes/static/built/bundle.js"
}
in your package.json and
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
in your pom.xml

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'
]
}
}

Remove server from react-boilerplate

How should one do to remove server folder from react-boilerplate? Question is also asked here by another person https://github.com/react-boilerplate/react-boilerplate/issues/2110.
Removing just server folder will not work because the webpack dev configuration is utilising it for hot reload as well as your npm start command starts express server from this folder.
If you want to remove server folder completely and still want the application to be working as it was like hot reloading etc, follow the below steps. We will require webpack dev server in that case:
Remove ./server folder manually.
Install webpack-dev-server and react-hot-loader as dev dependencies.
In your ./internals/webpack/webpack.dev.babel.js, do the following modifications:
Change entry to this:
entry: [
require.resolve('react-app-polyfill/ie11'),
'react-hot-loader/patch',
`webpack-dev-server/client?http://localhost:3000/`,
'webpack/hot/only-dev-server',
path.join(process.cwd(), 'app/app.js'), // Start with js/app.js
],
Add publicPath in output:
output: {
filename: '[name].js',
chunkFilename: '[name].chunk.js',
publicPath: `http://localhost:3000/`,
},
Add webpack dev server config property in the same file:
devServer: {
port: 3000,
publicPath: `http://localhost:3000/`,
compress: true,
noInfo: false,
stats: 'errors-only',
inline: true,
lazy: false,
hot: true,
open: true,
overlay: true,
headers: { 'Access-Control-Allow-Origin': '*' },
contentBase: path.join(__dirname, '..', '..', 'app', 'build'),
watchOptions: {
aggregateTimeout: 300,
ignored: /node_modules/,
poll: 100,
},
historyApiFallback: {
verbose: true,
disableDotRule: false,
},
},
In ./internals/webpack/webpack.base.babel.js, add the line:
devServer: options.devServer,
And finally, modify your start script in package.json as below:
"start": "cross-env NODE_ENV=development node --trace-warnings ./node_modules/webpack-dev-server/bin/webpack-dev-server --color --config internals/webpack/webpack.dev.babel.js",
And you are good to go!!
Just remove with rm -rf ./server if you feel harassed :)

Using Webpack for hot-loader and generating a physical file w/ ReactJs ES6

I have a ReactJs ES6 (ie 'import' keywords) app that uses gulp for generating a physical build file and webpack for hot-loading the changes to a virtual file. I wanted to combine the two services with npm start (which current loads webpack, not gulp).
server.js file
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
webpack.config.js file
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'build'),
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader'],
include: path.join(__dirname, 'src'),
exclude: /node_modules/
},
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
}
};
I thought based on webpack's output section, webpack would generate a physical file in my build folder while creating a virtual file in '/static/bundle.js'
Currently, the virtual file with hot-loader is working, but no physical file has been built in the 'build' path.
Am I correct that webpack can replace gulp and generate both a physical & virtual build file? If so, where is my code in err as far as creating a physical build file?
Thanks in Advance.
Solution:
My code is fine, I needed to add to my scripts in package.json:
.....
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"gulp": "gulp",
"all": "npm run build && npm run gulp"
.....
I then run "npm run all" and I can run webpack and gulp from one command

Resources