Failing to get docker to work with react and webpack - reactjs

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",

Related

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": "...",
...
}

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"),
},
}),
],
};

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

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

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

webpack configuration error

I tried to configure web pack for reacts web app, it kept telling me to use
npm install -D webpack-cli :
The CLI moved into a separate package: webpack-cli.
Please install 'webpack-cli' in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D
module.js:557
throw err;
^
when I did what it was asking me it gave me this error :
C:\Users\Desktop\lazabre1>webpack-dev-server
C:\Users\Desktop\lazabre1\webpack.config.js:59
new webpack.NoErrorsPlugin()
^
this is my webpack.config.js file :
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./src'
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
I have 2 questions: first - how to solve this problem //
second - what is the difference between npm install webpack and npm install webpack-cli.
You are using a configuration file written for Webpack 1 (I guess, by the use of the module.loader key and the NoErrorsPlugin) and using Webpack 4 (if you did not specify otherwise, and by the request to use the CLI which is not included by default anymore).
Upgrade your configuration by following the documentation and update the NoErrorsPlugin.
The webpack-cli is a package to use webpack from the command-line tool (what you are trying to do).

Resources