Changes are not reflected in webpack-dev-server running on docker - reactjs

I try react aplication for running docker
compiled successfully but I am plagued with the problem that changes to React files are not detected.
I tried add watch option and build producition mode but None of them worked
https://medium.com/#zwegrzyniak/docker-compose-and-webpack-dev-server-hot-reloads-b73b65d13d79
This article seems to be the most direct problem for me, but I'm not sure
this mycode
webpack.config.js
const publidDir = `${__dirname}/public`;
module.exports = {
entry: [
'./src/index.jsx',
],
output: {
path: publidDir,
publicPath: '/',
filename: 'bundle.js',
},
module: {
rules: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
},
}],
},
resolve: {
extensions: ['.js', '.jsx'],
},
watch: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
devServer: {
historyApiFallback: true,
contentBase: publidDir,
host: '0.0.0.0',
port: '3000',
open: true,
hot: true,
},
};
Dockerfile
FROM node:10.16.3-alpine
RUN mkdir -p /src
WORKDIR /src
COPY ./ ./
RUN yarn install
CMD ["yarn", "start"]
EXPOSE 3000
docker-compose.yml
version: "3"
services:
webpack:
build: ./docker
ports:
- "3000:3000"
volumes:
- ./docker/src:/docker/src
thanks

Related

Browser tab freezes when running webpack-dev-server in development mode using remote Module Federation module

Dependency versions:
webpack: 5.73.0
webpack-dev-server: 4.9.2
This occurs when running a host application via webpack-dev-server that consumes micro-apps via ModuleFederationPlugin.
Example host config:
module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
mode: "development", // success when changed to "production"
devServer: {
port: 3000,
client: {
overlay: false,
},
},
output: {
path: path.resolve(__dirname, "./build"),
publicPath: "/",
filename: "[name].[contenthash].js",
clean: true,
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["#babel/preset-react"],
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "Host",
remotes: {
ExampleModule: `ExampleModule#${
process.env.LOCAL_MODULE
? `http://localhost:3001/`
: "https://example.com/examplemodule/"
}remoteEntry.js`,
},
shared: [
{
react: { version: "16.13.0", singleton: true },
"react-dom": { version: "16.13.0", singleton: true },
},
],
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "public/index.html"),
}),
],
};
Example module config:
module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
mode: "development", // set to "production" for build that is served statically
devServer: {
static: { directory: path.join(__dirname, "public") },
port: PORT,
},
output: {
path: path.resolve(__dirname, "./build"),
publicPath:
process.env.NODE_ENV === "development"
? `http://localhost:${PORT}/`
: "https://example.com/examplemodule/",
filename: "[name].[contenthash].js",
clean: true,
},
resolve: {
extensions: [".js", ".jsx"],
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["#babel/preset-react"],
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "ExampleModule",
library: { type: "var", name: "ExampleModule" },
filename: "remoteEntry.js",
exposes: {
"./ExampleModule": "./src/ExampleModule",
},
shared: [
{
react: { version: "16.13.0", singleton: true },
"react-dom": { version: "16.13.0", singleton: true },
},
],
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, "public/index.html"),
}),
],
};
When running both the host and ExampleModule via webpack-dev-server, the app works, consuming the module from localhost:3001 without issue.
However, when running the host via webpack-dev-server and consuming the production build of the module from a remote URL (using https://example.com/examplemodule/remoteEntry.js in the example above), the page becomes completely unresponsive immediately after the remote entry file is fetched. There is no output in the JavaScript console due to this, and there is no feedback in the CLI output, so there are no error messages to report. This occurs in any browser, and I am on macOS Monterey.
This only occurs when running webpack-dev-server for the host in the "development" Webpack mode. Switching to production mode will fix this issue. It also will not occur when serving the static build of the host, regardless of the Webpack mode used when creating the build.
Unfortunately, this is difficult to reproduce. I attempted to make an isolated example with a React host and remote module using the same dependencies and very similar webpack configs, but I cannot reproduce the issue this way yet, so it may be specific to application code I cannot share. I'm wondering if anyone else has experienced this.

GCP 500 Erroring despite files uploaded

I am trying to deploy a React app for the first time and can't seem to figure out why it is not working...
Here is what I have tried:
git clone [repo url]
cd repo/client
npm i
npm build
cd build
vim app.yaml
Entered the following:
env: standard
runtime: nodejs12
handlers:
- url: /
static_files: build/\1
upload: build/.*
gcloud app deploy app.yaml --verbosity=debug
Output:
INFO: Manifest: [{'index.html': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/226a7f7ca6cf647c5457b709cef629bb950fbc9a', 'sha1Sum': '226a7f7ca6cf647c5457b709cef629bb950fbc9a'}, '961.index.bundle.js': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/907d0e7384a3b3060ba5b0bf522d5c6e99f38d39', 'sha1Sum': '907d0e7384a3b3060ba5b0bf522d5c6e99f38d39'}, '1': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/12de9963495774159595601cd57e64c1febb1e9a', 'sha1Sum': '12de9963495774159595601cd57e64c1febb1e9a'}, 'app.yaml': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/e3979db38f5ace413d6dff3d8f7e30bda5922438', 'sha1Sum': 'e3979db38f5ace413d6dff3d8f7e30bda5922438'}, 'index.bundle.js.LICENSE.txt': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/e74ccdb144d7d0ada75f8115a86b4c93444238cf', 'sha1Sum': 'e74ccdb144d7d0ada75f8115a86b4c93444238cf'}, 'index.bundle.js': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/4bca86ed5f442588b4cd5a7dc59719afe5c67015', 'sha1Sum': '4bca86ed5f442588b4cd5a7dc59719afe5c67015'}, 'source-context.json': {'sourceUrl': 'https://storage.googleapis.com/staging.reactfrontend-336116.appspot.com/a0d08448a753f65abae14090837cf7c12a173cad', 'sha1Sum': 'a0d08448a753f65abae14090837cf7c12a173cad'}}]
As you can see the all files are correctly uploaded (there are no assets), but when I access the URL I get a 500 Server error: "The server encountered an error and could not complete your request."
I'm not really sure what I've done wrong... I can run the React app locally without any issues
Webpack:
const HtmlWebpackPlugin = require('html-webpack-plugin');
// hot reload CSS:
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
module.exports = {
entry: './src/index.jsx',
output: {
path: path.join(__dirname, 'build'),
filename: 'index.bundle.js',
assetModuleFilename: 'images/[hash][ext][query]'
},
target: 'web',
devServer: {
historyApiFallback: true,
hot: true,
open: true,
port: 3000
},
performance: {
hints: false
},
resolve: {
extensions: ['.js', '.jsx', '.json']
},
module: {
rules: [
{
test: /\.(scss|css)$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
type: 'asset/inline'
},
{
test: /\.(js|jsx)$/,
use: 'babel-loader'
}
]
},
plugins: [new MiniCssExtractPlugin(), new HtmlWebpackPlugin({ template: './src/index.html' })]
};

Got a blank white page after deploying react app to gitlab pages

I want to deploy my react app (not create-react-app, built from skratch) to gitlab pages, all jobs are passed successfully, but the page is not working correctly. I have just a blank white page.
my .gitlab-ci.yml
stages:
- build
- deploy
build:
image: node:latest
stage: build
script:
- npm install
- npm run build
artifacts:
paths:
- build/
pages:
image: alpine:latest
stage: deploy
variables:
GIT_STRATEGY: none
script:
- mv build public
- cd public
artifacts:
paths:
- public
My webpack, I merge common with prod
webpack.common.js
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx']
},
entry: {
index: './src/index.tsx'
},
output: {
filename: "[name].[chunkhash].js",
chunkFilename: "[name].[chunkhash].js",
path: path.resolve(__dirname, "public"),
publicPath: "/"
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[contenthash].css', chunkFilename: '[name].[contenthash].css' }),
new HtmlWebpackPlugin({
template: "src/index.html",
inject: "body",
minify: {
minifyCSS: true,
minifyJS: true,
collapseWhitespace: true
}
}),
],
module: {
rules: [
{
test: /\.(css|scss|sass)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/i,
use: ['file-loader']
},
{
test: /\.html$/,
use: [{ loader: 'html-loader' }]
},
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /(node_modules|bower_components|prod)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react', '#babel/preset-typescript']
}
}
}
]
}
}
webpack.prod.js
module.exports = merge(common, {
mode: 'production',
optimization: {
minimizer: [
new UglifyJsPlugin({
test: /\.js(\?.*)?$/i,
})],
moduleIds: 'deterministic',
runtimeChunk: 'single',
splitChunks: {
name: 'runtime',
chunks: 'all'
}
}
})
package.json
"scripts": {
"start": "webpack-dev-server --config webpack.dev.js --open",
"build": "webpack --config webpack.prod.js"
},
As I mentioned locally works fine, both dev server and build.
I have no console error, just a warning:
Error with Permissions-Policy header: Unrecognized feature:
'interest-cohort'.
and
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://gitlab.com/users/sign_in with MIME type text/html. See
https://www.chromestatus.com/feature/5629709824032768 for more
details.
I logged out, when I logged in I get 401err
GET https://projects.gitlab.io/auth?code=2.... net::ERR_ABORTED 401
project is public
Had the same issue. Turned out homepage attribute in package.jsonwas containing incorrect site url.
You need to add this attribute (if not already) at the top of package.json, and make sure it is pointing to the gitlab pages url for your site.
{
"homepage": "GITLAB_PAGES_URL",
"name": "...",
...
}

Failing to get docker to work with react and webpack

So, I've been working on this problem for the better part of a week now and I feel like I've gotten nowhere despite reading a lot of articles on this very topic and reading through a lot of stack overflow questions. I've got the following files docker-compose.yml and Dockerfile.dev that I'm trying to use in following this article, https://blog.bam.tech/developper-news/dockerize-your-app-and-keep-hot-reloading. A few differences between my implementation and that article. I can't use the node_modules directory as far as I'm aware from my machine (OSX), as I'm trying to run Docker with a linux environment, so I have to run npm install from within Docker. I don't have an api implemented yet (that is coming, I just want to get this to work first), so all references to api have been removed.
This is my docker-compose.yml:
version: '3'
services:
server:
container_name: server
build: ./server
ports:
- '80:80'
links:
- app:app
app:
container_name: app
build:
context: ../retail
dockerfile: Dockerfile.dev
ports:
- '9000:9000'
volumes:
- ../retail:/usr/src/app/
environment:
- NODE_ENV=development
- NPM_CONFIG_PRODUCTION=false
db:
container_name: database
build: ./database
environment:
POSTGRES_PASSWORD: supersecretpasswordthatnobodyknows
POSTGRES_USER: devsuperuser
POSTGRES_DB: lending
restart: always
ports:
- '5432:5432'
volumes:
- /var/lib/postgresql/data
And this is my Dockerfile.dev referenced above:
FROM node:alpine
WORKDIR /usr/src/app
COPY ./package.json ./.npmrc ./
RUN npm install webpack webpack-cli webpack-server webpack-hot-client -g
RUN npm link webpack webpack-dev-server && npm install
EXPOSE 9000
CMD ["npm", "run", "start:dev"]
Some of the things I've tried are in the above code. Such as setting NPM_CONFIG_PRODUCTION to false. And installing everything webpack globally and then linking it. I found if I didn't do the latter I got errors about not being able to find webpack. I've tried multiple combinations of different ideas from a whole host of articles, but no matter what I've tried I'm constantly getting issues about some missing module or another.
I'm just wondering if someone can help me make this article work for me while needing to do an npm install. Or perhaps even some way that I can do the npm install locally and not need to do it in the Docker container (because that works).
EDIT:
I'm adding another file and part of a file that may or may not be relevant below in response to a comment asking for them.
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
module.exports = {
devtool: 'eval-source-map',
context: __dirname,
entry: [
'babel-polyfill',
// 'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:9000',
'webpack/hot/only-dev-server',
'./src/index.js',
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
publicPath: '/',
},
devServer: {
disableHostCheck: true,
historyApiFallback: true,
inline: false,
port: 9000,
hot: true,
proxy: {
'/v1': {
target: 'an IP address',
},
},
},
module: {
loaders: [
{
test: /\.(css|scss)$/,
use: [
'style-loader',
{ loader: 'css-loader' },
'sass-loader',
],
},
{
test: /\.(png|jpg|svg|woff|woff2|ttff|eot|ttf)$/,
loader: 'url-loader?limit=25000',
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [
path.join(__dirname, 'src'),
],
exclude: /node_modules/,
options: {
// This is a feature of `babel-loader` for Webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// plugins: ['react-hot-loader/babel'],
},
},
{
test: /config\.js$/,
loaders: 'string-replace-loader',
query: {
multiple: [
{ search: '{{API_SERVER}}', replace: '' },
],
},
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
},
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.LoaderOptionsPlugin({ options: { postcss: [autoprefixer] } }),
],
};
And my script definition for start:dev in my package.json
"start:dev": "webpack-dev-server --host 0.0.0.0 --hot --inline",

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 :)

Resources