GCP 500 Erroring despite files uploaded - reactjs

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

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.

Webpack & NGINX configuration for React app with set path prefix

I'm working on a React app and I have it working when I deploy it as a Docker container, in a Rancher cluster, to what I'll call a "normal" endpoint. Meaning if I set up the endpoint to be test.site.com, everything works fine. The problem is my company is insisting on using path to direct traffic to different services. For example, test.site.com/my-site will direct traffic to my React app, but test.site.com/other-site directs traffic to another service. I'm having an issue where when I deploy my site to test.site.com/my-site, my app can't seem to resolve some of its assets. Opening the console in the browser gives errors such as:
GET https://test.site.com/cesium/Cesium.js net::ERR_ABORTED 405
GET https://test.site.com/cesium/Widgets/widgets.css net::ERR_ABORTED 404
GET https://test.site.com/bundle.js net::ERR_ABORTED 404
(Cesium is a library I'm using in my app https://cesium.com/blog/2018/03/05/integrating-cesium-and-react/)
I've only recently started working with webpack, so I think there's probably some configuration there to fix this? Here's the relevant config files.
webpack.config.js
const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const HtmlPlugin = require('html-webpack-plugin')
const HtmlTagsPlugin = require('html-webpack-tags-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const dotenv = require('dotenv')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
},
extensions: ['.jsx', '.js'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.(png|svg|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
],
},
devServer: {
historyApiFallback: {
index: '/',
},
},
externals: {
cesium: 'Cesium',
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.config().parsed), // it will automatically pick up key values from .env file
}),
new CopyWebpackPlugin({
patterns: [
{
from: 'node_modules/cesium/Build/Cesium',
to: 'cesium',
},
],
}),
new HtmlPlugin({
template: './src/index.html',
}),
new HtmlTagsPlugin({
append: false,
tags: ['cesium/Widgets/widgets.css', 'cesium/Cesium.js'],
}),
new webpack.DefinePlugin({
CESIUM_BASE_URL: JSON.stringify('/cesium'),
}),
],
}
Dockerfile
FROM node:14-slim AS builder
ENV NODE_ENV production
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
FROM nginx:1.21.0-alpine as production
ENV NODE_ENV production
COPY --from=builder /app/build /usr/share/nginx/html
RUN echo $(ls -1 /usr/share/nginx/html)
RUN chown nginx:nginx -R /usr/share/nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN echo $(ls -1 /etc/nginx/conf.d/)
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
nginx.conf
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

webpack options has an unknown property 'hotOnly'. Invalid options object. Dev Server has been initialized using an options object

I am running the command npx webpack-dev-server --mode development in my react application and getting the preceding error.
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'hotOnly'. These properties are valid:
Below is my webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};
Any idea what is causing this issue?
So devServer|Webpack config is related to Options for webpack-dev-server
If your webpack is using webpack-dev-server version 4 you should use this migration guide
// your v3 config
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
in v4 will be
devServer: {
// contentBase
static : {
directory : path.join(__dirname, "public/")
},
port: 3000,
// publicPath
devMiddleware:{
publicPath: "https://localhost:3000/dist/",
}
// hotOnly
hot: "only",
},
It seems like the updated version of webpack doesn't support the property hotOnly, we should use the option hot instead. You can see a GitHub issue associated with this here.
devServer: {
hot: "only", // hot:true
},
The latest versions automatically apply HotModuleReplacementPlugin plugin when you set hot: true, so please check you don't have HotModuleReplacementPlugin in your plugins if you have hot: true/hot: "only". You will get a warning as " [webpack-dev-server] "hot: true" automatically applies HMR plugin, you don't have to add it manually to your webpack configuration." if you have the preceding settings.
plugins: [new webpack.HotModuleReplacementPlugin()],
If you are getting error "static heartbeatInterval = 1000; SyntaxError: Unexpected token =", make sure to use the node version is >= 12.13.0 as per the guide here.
If everything is done, you should be able to see an output as preceding when you run npx webpack-dev-server --mode development.
Thanks, #Tushar Mistry for providing the migration guide.
Below is my completed webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
static: {
directory: path.join(__dirname, "public/"),
},
port: 3000,
devMiddleware: {
publicPath: "https://localhost:3000/dist/",
},
hot: "only",
},
};
Or you can also use the old version as below.
"webpack": "4.41.5",
"webpack-cli": "3.3.10",
"webpack-dev-server": "3.10.1"
For me, comma was missing after devMiddleware property causing error.
Solved by installing an older version of webpack
"webpack-dev-server": "3.10.1"

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

Why i get hashed .jpeg file when running 'npm run build' with webpack

Im a new beginner on develop react app.
Im trying to figure out how to set up my webpack.config.js file.
I have following ended up with this structure as you can see on the picture link below.
My question is: When im running 'npm run build' , its hashing the picture and put it into the /dist folder. How can i configure so it does not?
Because im using copyWebpackPlugin() to copy my images and push it to the dist folder, but i dont want the picture which i marked with arrow.
If anyone have some advice just bring it on.
This is how my webpack.config.js file look like:
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader"
},
{
test: /\.s?css$/,
loader: ["style-loader", "css-loader"]
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: "url-loader?limit=100000"
}
]
},
resolve: { extensions: [".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
filename: "bundle.js"
},
devtool: "cheap-module-eval-source-map",
devServer: {
contentBase: path.join(__dirname, "public/"),
proxy: {
"/api/*": {
target: "http://localhost:3000/",
secure: "true"
}
},
port: 4000,
publicPath: "http://localhost:4000/dist/",
hotOnly: true,
historyApiFallback: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
filename: "index.html",
template: "./public/index.html"
}),
new CopyWebpackPlugin([{ from: "public/images", to: "images" }])
]
};
I would suggest instead of copy-webpack-plugin use file-loader to copy images
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [{
loader: 'file-loader',
options: {
name: 'images/[name].[ext]',
}
}]
}
if you want hash instead of name
name: 'images/[hash].[ext]',
Package
npm install --save-dev file-loader
It is because the url-loader has a default fallback to file-loader. So if your image is bigger than the limit you have set for url-loader, it does not rewrite the image to base64 data:image in your css, instead gives it to file-loader and it copies that image to your dist folder (output path).
So if you do not want this, disable the fallback option for url-loader
But I also think you should have configure your webpack to copy the files with file-loader properly instead that copy plugin. But you know...
I would give you an example based on your config but I am currently on mobile so I can't code right now.

Resources