ReactJs Image Not found on production mode - reactjs

I have pushed my app on my repo.
The images are imported to the path:
react-blog-app/blob/gh-pages/static/media/_resized_300.353f8ae3.jpg
However on the page the images are not found.
The URL is pointing to
react-blog-app/static/media/_resized_300.353f8ae3.jpg
I have added 'contentBane' on config.json
{
"apiEndpoint": "https://jsonplaceholder.typicode.com/posts" ,
"devServer": {
"contentBase": "./build"
}
}
Do you have any suggestion to fix this issue?
Thanks in advance.

I think you didn't add file-loader to module.rules. the code below is minimal webpack configuration for react app.
webpack.config.js
require("dotenv").config();
const path = require("path");
const webpack = require("webpack");
// Plugins
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
mode: process.env.NODE_ENV || "production",
entry: "./src/index.jsx",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
resolve: { extensions: ["*", ".js", ".jsx"] },
// externals: {
// "react-js": "React",
// "react-dom": "ReactDOM"
// },
module: {
rules: [
{
test: /\.(js|jsx|es6|es|mjs)$/,
include: path.resolve(__dirname, "src"),
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader",
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ["file-loader"]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: "./src/index.ejs",
filename: "index.html",
title: "My React App",
inject: "body",
scriptLoading: "defer",
cache: true
}),
new webpack.ProgressPlugin()
],
devtool: "source-map",
devServer: {
hot: true,
port: 8000,
open: true
}
};
.babelrc
{
"presets": ["#babel/preset-react"],
"env": {
"development": {
"presets": [["#babel/preset-react", { "development": true }]]
}
}
}
package.json
"scripts": {
"start:dev": "cross-env NODE_ENV=development \"webpack-dev-server\"",
"build": "webpack"
}

Related

WEBPACK with React router gives 404 while serving the build

Recently i am learning webpack with react and i build a app that runs wells in Dev enviroment but when i build the app and tries to change the route it throws 404 error.
Here are my webpack Config.
webpack.common.js
const path = require("path");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, "..", "./src/index.tsx"),
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js"],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
},
],
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test:/\.(?:ico|gif|png|jpg|jpeg)$/i,
type:'asset/resource'
},
{
test:/\.(woff(2)?|eot|ttf|otf|svg)$/i,
type:'asset/inline'
}
],
},
output: {
path: path.resolve(__dirname, "..", "./build"),
filename: "bundle.js",
},
plugins: [
new HTMLWebpackPlugin({
template: path.resolve(__dirname, "..", "./public/index.html"),
filename:'index.html'
}),
// new CopyWebpackPlugin({
// patterns:[{from:"src",to:'dest'}]
// })
],
};
webpack.dev.js
const ReactRefreshWebpackPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const path=require('path')
module.exports={
mode:"development",
devServer:{
hot:true,
open:true,
historyApiFallback: { index: "/", disableDotRule: true },
port:3001
},
devtool:'cheap-module-source-map',
plugins:[
new ReactRefreshWebpackPlugin()
]
}
webpack.prod.js
module.exports={
mode:"production" ,
}
i changed lots of configuration like public path and other, but it didn't help.

Webpack Source Map Export Compiled JS

I was using webpack 3, there was no hot reload issue and then I upgraded to webpack 5.
Webpack version: ^5.50.0, React version: 17.0.2
Webpack source map doesn't work properly. I attached a picture of output at the bottom.
When I read webpack documentation, there is no difference between my config with offical config.
Here is my webpack hot config for development;
const webpack = require('webpack') //to access built-in plugins
const HtmlWebpackPlugin = require('html-webpack-plugin') //installed via npm
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const vendorArray = require('./vendors')
const path = require('path')
const Dotenv = require('dotenv-webpack')
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
main: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://0.0.0.0:3002',
'webpack/hot/only-dev-server',
'./src/main.js'
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash:8].js'
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss', '.json']
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: './config/webpack/style-loader'
},
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', { targets: 'defaults' }], '#babel/preset-react'],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
[
'#babel/plugin-proposal-decorators',
{
legacy: true
}
]
]
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)([\?]?.*)$/,
type: 'asset/resource'
}
]
},
plugins: [
new webpack.DefinePlugin({
APP_ENV: JSON.stringify('dev')
}),
new HtmlWebpackPlugin({
template: './public/index.html',
templateParameters: {
recaptchaSiteKey: '6LfbRrEZAAAAAL1EiyUSq1yzEw1xqleak2xC2pzi',
intranetLogin: true
}
}),
new MiniCssExtractPlugin(),
new Dotenv({
path: path.resolve(__dirname, './../../.env.test')
})
]
}

Webpack Dev Server (Uncaught SyntaxError: Unexpected token '<' )

Building TS/SASS with Webpack works fine, running this through VSCode Live Server plugin renders the index.html perfectly to the app folder.
Running webpack-dev-server with it looking at the same app folder does not. The page opens but there is a Javascript error Uncaught SyntaxError: Unexpected token '<'
And the page does not render the JS/CSS.
webpack.config.js
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
open: 'http://localhost',
port: 80,
publicPath: path.resolve(__dirname, 'app'),
hot: true
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
tsconfig.json
{
"compilerOptions": {
"sourceMap": true
}
}
main.ts
console.log('Main.ts has loaded')
import './styles/main.scss'
Any help with this would be appreciated, I'm losing my mind lol.
My issue was with syntax in the webpack.config.js file.
I was neglecting to insert a comma at the end of the last entry in every object and array, believing it not to be necessary.
Here is a working config:
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app'),
},
devServer: {
open: 'http://localhost',
port: 80,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
}

Window is not defined after a build with Webpack

I am developing a reactJS application and also I am using WebPack 4.29.6 the problem that I face here it is that locally it works everything perfect when I run the npm run dev command while when I want to deploy in server I don't know how to do it I am building the app with the build:production command then it generates /dist folder inside with all files now here I try to run bundle.js it gives me this error: ReferenceError: window is not defined.
these are command's that i use to start my app:
"scripts": {
"dev": "cross-env webpack-dev-server --config ./webpack.config.dev.js --mode development",
"build:production": "cross-env webpack --config webpack.config.production.js --mode production"
}
this is my webpack.config.common.js
const path = require('path');
const webpack = require('webpack');
const outputPath = path.join(__dirname, '/dist');
const port = process.env.PORT || 4000;
module.exports = {
context: __dirname,
entry: './src/index.jsx',
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: outputPath,
publicPath: '/',
filename: 'bundle.js',
sourceMapFilename: 'bundle.map',
},
devServer: {
port,
historyApiFallback: true,
compress: true,
contentBase: './dist',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader',
},
],
},
{
test: /\.css$/,
use: ['css-loader'],
},
{
test: /\.svg$/,
loader: 'svg-inline-loader',
},
{
test: /\.(png|jpg|gif|woff(2)?|ttf|eot|svg)$/,
exclude: [
/\.(js|jsx|mjs)$/,
/\.html$/,
/\.json$/,
/\.(less|config|variables|overrides)$/,
],
use: [
{
loader: 'file-loader',
},
],
},
],
},
plugins: [
new webpack.ProvidePlugin({
Promise: 'es6-promise-promise',
}),
],
};
this is my webpack.config.dev.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackCommonConfig = require('./webpack.config.common');
module.exports = merge(webpackCommonConfig, {
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, '/index.html'),
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
devtool: 'inline-source-map',
devServer: {
hot: true,
open: true,
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:3000',
}),
},
});
this is my webpack.config.production.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpackCommonConfig = require('./webpack.config.common');
module.exports = merge(webpackCommonConfig, {
mode: 'production',
plugins: [new webpack.EnvironmentPlugin({ NODE_ENV: 'production' })],
optimization: {
minimizer: [
// we specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true,
},
sourceMap: true,
}),
],
},
devtool: 'source-map',
devServer: {
compress: true,
},
});
It may be late to answer but it may help someone else. I also had the ReferenceError: window is not defined. issue with Webpack 4, and found that adding globalObject: 'this' line to the output section in webpack config file fixed my problem:
output: {
globalObject: "this",
filename: "[name].js",
path: path.join(__dirname, "build/package"),
publicPath: "/resources/",
}
You can see the issue was discussed here
and the Webpack documentation about the globalObject setting here.
Using global worked for me.
const window = global.window
if (window && window.localStorage) {
const storageLogLevel = window.localStorage.getItem(LOG_LEVEL_KEY)
switch (storageLogLevel) {
case LogLevel.DEBUG:
logLevel = 0
break
case LogLevel.INFO:
logLevel = 1
break
case LogLevel.WARNING:
logLevel = 2
break
case LogLevel.CRITICAL:
logLevel = 3
break
default:
logLevel = 1
}
}

React-hot-loader with SSR

I'm trying to figure out how to correctly implement react-hot-loader in my new SSR app, I've been able to do it fine in previous projects but I'm new to SSR so can't figure it out.
Here is my webpack.config.client:
const path = require("path");
const merge = require("webpack-merge");
const baseConfig = require("./webpack.config.base.js");
const client_path = path.resolve(__dirname, "public");
const config = {
name: "client",
target: "web",
entry: ["react-hot-loader/patch", "./src/client/client.js"],
output: {
path: client_path,
filename: "bundle.js"
},
resolve: {
extensions: [".js", ".jsx"]
}
};
module.exports = merge(baseConfig, config);
Here is my webpack.config.server:
const path = require("path");
const merge = require("webpack-merge");
const baseConfig = require("./webpack.config.base.js");
const webpackNodeExternals = require("webpack-node-externals");
const server_path = path.resolve(__dirname, "build");
const config = {
target: "node",
name: "server",
entry: ["react-hot-loader/patch", "./src/index.js"],
output: {
filename: "bundle.js",
path: server_path
},
resolve: {
extensions: [".js", ".jsx"]
},
externals: [webpackNodeExternals()]
};
module.exports = merge(baseConfig, config);
and webpack.config.base;
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
enforce: "pre",
loader: "babel-loader"
exclude: /node_modules/,
options: {
presets: [
"es2015",
"react",
"stage-0",
[
"env",
{ targets: { browsers: ["last 2 versions"] } }
]
],
plugins: [
"react-hot-loader/babel",
["transform-class-properties", { spec: true }]
]
}
}]
}
};
and package.json scripts:
"scripts": {
"dev": "npm-run-all --parallel dev:*",
"dev:server": "nodemon --w build --exec \"node build/bundle.js\"",
"dev:build-server": "webpack --config webpack.config.server.js --w",
"dev:build-client": "webpack --config webpack.config.client.js --w"
},
and if helpful link to github - https://github.com/dmartss/health2

Resources