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

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

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.

Unable to start my react application and getting error in webpack server

I don't know where am going wrong
Am not sharing all package.json but whatever required am sharing.
here is my package.json
"scripts": {
"develop": "webpack serve --hot --port 8080 --disable-host-check --config webpack.develop.js",
},
"engines": {
"node": ">=10"
},
"devDependencies": {
"react-hot-loader": "^4.12.20",
"react-test-renderer": "^17.0.1",
"typescript": "4.1.2",
"webpack": "^5.70.0",
"webpack-bundle-analyzer": "^4.2.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
web.develop.js
const commonConfig = require('./webpack.config')
module.exports = {
...commonConfig,
output: {
...commonConfig.output,
publicPath: 'http://localhost:8080/',
},
mode: 'development',
module: {
rules: [
...commonConfig.module.rules,
{
test: /\.(js|jsx|ts|tsx)?$/,
use: 'react-hot-loader/webpack',
include: /node_modules/,
},
],
},
devServer: {
index: 'index.html',
hot: "only", // hot:true
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
},
plugins: [...commonConfig.plugins],
}
error:
[webpack-cli] Error: Unknown option '--disable-host-check'
[webpack-cli] Run 'webpack --help' to see available commands and options
if i use this command
"develop": "webpack serve --hot --port 8080 --allowed-hosts all --config webpack.develop.js"
am getting below 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 'index'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?,
onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
i removed index and localhost up and running but build.js is not created in dist folder.
webpack.config.js
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const dotenv = require('dotenv')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin
// Create .env file if it does not exist
if (!fs.existsSync('.env')) {
fs.copyFileSync('.env_example', '.env')
}
dotenv.config()
if (!process.env.POSTS_SERVER_URL) {
// webpack 5 is stricter about environment variables. The POSTS_SERVER_URL
// environment variable was not mentioned in the README so default it for
// those developers who may have created a .env file without the variable.
process.env.POSTS_SERVER_URL = 'http://127.0.0.1:3000'
}
const PATHS = {
app: path.join(__dirname, 'src/index.tsx'),
}
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
module: {
rules: [{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/,
sideEffects: false,
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'file-loader'},
{
test: /\.(scss|css)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[hash:base64]",
auto: true
},
sourceMap: true
}
},
{
loader: 'sass-loader'
}
]
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.css'],
modules: [__dirname,
'node_modules'
],
fallback: { buffer: false },
},
devtool: 'source-map'
}
Can anyone suggest me where is my configuration is going wrong

Cross-env not changing env variable when running yarn

I am trying to setup the environment so that when i choose to run prod it runs the prod settings and when i choose to run dev it runs the dev server, currently my package.json scrips look like this :
"scripts": {
"build:dev": "cross-env NODE_ENV=developement webpack",
"build:prod": "cross-env NODE_ENV=production webpack",
"start:dev": "cross-env NODE_ENV=developement webpack-dev-server ",
"start:prod": "cross-env NODE_ENV=production webpack-dev-server "
},
webpack config file:
const webpack = require("webpack");
const path = require("path");
const dotenv = require("dotenv");
module.exports = {
//Entry file for webpack.config
entry: "./src/index.js",
//Target specific use of project ie. nodejs project we use node value
target: process.env.NODE_ENV === "dev" ? "node" : "web",
//Dev server meant for hosting local server for developement
devServer: {
contentBase: path.resolve(__dirname, "public"),
historyApiFallback: true,
port: 8080,
},
//Modules are used to set rules to build specific file types
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/env", "#babel/react"],
plugins: [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-class-properties",
],
},
},
],
},
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
{
test: /\.(css|sass|scss)$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
sourceMap: true,
importLoaders: 2,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
},
{
test: /\.svg$/,
use: [
{
loader: "svg-inline-loader",
options: {
limit: 10000,
},
},
],
},
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
],
},
externals: {
// require("jquery") is external and available
// on the global var jQuery
"jquery": "jQuery"
},
//Changes how modues are resolved
resolve: {
extensions: ["*", ".js", ".jsx", ".ts", ".tsx"],
},
//Output is setup to serve the bundle.js file to be served to web browser
output: {
path: path.resolve(__dirname, "public"),
filename: "bundle.js",
publicPath: "/",
},
//Prevent bundling of certain packages
externals: {
"react-native": true,
},
//A javascript object used to do various extra things for webpack
plugins: [
new webpack.DefinePlugin({
"process.env": JSON.stringify(dotenv.config().parsed),
}),
],
};
and i do:
console.log(process.env.NODE_ENV)
inside my homepage jsx, but everytime I run it even when i do yarn start:prod it console.logs development and not production, why is cross-env not successfully changing the NODE_ENV to production when i run this?
In order to copy env variable into webpack, you have to use webpack. DefinePlugin as you have done in your configuration file which looks like you're trying to copy all things into webpack.
Anyway if you want to use the value from cross-env, you would have do the same thing by using DefinePlugin plugin but input the specific value NODE_ENV as following:
webpack.config.js
{
// ...
plugins: [
// ...
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
],
}

react styled components not working in production

I have been able to work with styled-components on webpack dev server without any problem but the styles are not getting added when building the project for production with webpack -p --progress --colors or running webpack -d --progress --colors --watch
The only style added in production is an empty style
<style data-styled="" data-styled-version="4.4.1"></style>
in the webpack.config.js i have the following rules that is running for both dev and production:
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
},
]
},
Plugins, note that debug is used to if is production build
plugins: debug ? [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'template.html')
})
] : [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production"),
},
}),
new CleanWebpackPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new UglifyJsPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'template.html')
})
],
dev server settings:
devServer: {
contentBase: BUILD_DIR,
historyApiFallback: true,
watchContentBase: true,
port: 9000
},
do you have a global style created with createGlobalStyle that contains a css #import? Removing the import from my site just fixed the issue for me. (sounds like the same issue).
https://github.com/styled-components/styled-components/issues/2911#issuecomment-592012166

dev-server taking lot time to rebuild project in webpack 4

i developed react app,before that i built same app on webpack v3 now i upgrade to v4.on v3 dev-server it worked fine but on v4 it is taking lot of time to build and every time its building whole project again(may be that's why)
my webpack.dev.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize:false,
importLoaders: 1,
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},{
test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: "file-loader",
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true,
host:'0.0.0.0',
disableHostCheck: true,
}
};
and my scripts in package.json
"scripts": {
"start": "node server/server.js",
"build": "webpack --mode production --config=webpack.prod.js",
"dev": "webpack --mode development --config=webpack.dev.js",
"dev-server": "webpack-dev-server --config=webpack.dev.js"
}
it showing me error
ou are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) to ensure you have the correct code for your production build.
but if console my process.env.NODE_ENV varialbe it showing me developement
i have two problems with dev-server on development mode
1) how can i reduce time of rebuilding on dev-server
2)on development mode also why it showing me production error.
Your development server is being run in production mode because you haven't set the --mode development argument in your dev-server NPM script. It seems like it isn't required since webpack-dev-server is, after all, a development server, but the argument is still necessary.
"dev-server": "webpack-dev-server --mode development --config webpack.dev.js"
To speed up the build in development, inject all CSS into the HTML with style-loader instead of extracting the CSS to a separate file. See the following code where I removed mini-css-extract-plugin and its loader.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.s?css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize:false,
importLoaders: 1,
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true,
host:'0.0.0.0',
disableHostCheck: true,
}
};
Building source maps will slow the build down as well, so consider if you truly need them.
The answer is: you are using the inline-source-map devtool which causes the build & rebuild process super slow.
According to the Official Webpack Document, they said:
Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically.
For more information, you could read it here: https://webpack.js.org/configuration/devtool/#devtool
Hopefully, that helps!
Adding caching to babel-loader can shave off some time:
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
cacheCompression: false
}
}
]
}
https://github.com/babel/babel-loader#options
I have had the same issue and i completely remove source map for development and now is super-fast.My webpack.common.js file looks like this
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: '[name].[hash].js',
path: path.resolve('./dist')
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
},
{
loader: 'eslint-loader'
}]
}, {
test: /\.s?css$/,
use: [
{
loader: 'css-loader',
options: {
sourceMap: false
}
},
{
loader: 'sass-loader',
options: {
sourceMap: false
}
}
]
}]
},
optimization: {
minimize: true
},
plugins: [
new HtmlWebPackPlugin({
template: 'index.html'
}),
new CleanWebpackPlugin()
]
};
and my webpack.dev.js looks like this one
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devServer: {
host: 'localhost',
disableHostCheck: true,
port: 3000,
open: true,
historyApiFallback: true
}
});
With this aproach we losing source-map in development and get fast at speed,if you really need source-mapping in dev-mode choose some light-weight source-map like cheap-eval-source-map and change it when you go in production build to inline-source-map because inline-source-map decreases dramatically size of main.js || bundle.js file.

Resources