On starting Styleguidedist server it fails with Module parse failed: Unexpected token - reactjs

Im trying to start my style guide server but it keeps throwing following error:
I believe this occurs when the babel loaders are not configured for jsx files. But this isnt true as I am able to start my project without errors. But when I try to start the style guide I end up with this.
Here is my styleguide config file
module.exports = {
title: 'Component Library',
webpackConfig: Object.assign(
{},
require("./config/webpack/webpack.dev.config.js"),
{
/* Custom config options if required */
}
),
components: "source/components/**/*.jsx",
template: {
head: {
links: [
{
rel: "stylesheet",
href:
"https://fonts.googleapis.com/css?family=Poppins:400,400i,600,600i,700,700i&display=swap"
}
]
}
},
theme: {
fontFamily: {
base: '"Poppins", sans-serif'
}
},
styles: function styles(theme) {
return {
Playground: {
preview: {
backgroundColor: '#29292e'
},
},
Code: {
code: {
fontSize: 14,
},
},
};
},
};
Here is my webpack config
var webpack = require('webpack');
var path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const WebpackAssetsManifest = require('webpack-manifest-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const reactLoadablePlugin = require('react-loadable/webpack')
.ReactLoadablePlugin;
const workboxPlugin = require('workbox-webpack-plugin');
module.exports = (env) => ({
mode: 'development',
entry: path.join(__dirname, '../../index.js'),
output: {
filename: '[name].bundle.[hash].js',
chunkFilename: '[name].bundle.[hash].js',
path: path.join(__dirname, '../../../build'),
publicPath: '/'
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
// cacheGroupKey here is `commons` as the key of the cacheGroup
name(module, chunks, cacheGroupKey) {
const moduleFileName = module
.identifier()
.split('/')
.reduceRight(item => item);
const allChunksNames = chunks.map(item => item.name).join('~');
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
},
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: path.resolve(__dirname, 'node_modules'),
loader: 'babel-loader'
},
{
test: /\.svg(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
'svg-transform-loader'
]
},
{
test: /\.png(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.EnvironmentPlugin({
APP_ENVIRONMENT: process.env.APP_ENVIRONMENT,
API_KEY: process.env.API_KEY,
AUTH_DOMAIN: process.AUTH_DOMAIN,
DB_URL: process.env.DB_URL,
PROJECT_ID: process.env.PROJECT_ID
}),
new CleanWebpackPlugin({
path: path.join(__dirname, '../../../build')
}),
new WebpackAssetsManifest({
fileName: 'asset-manifest.json'
}),
new HtmlWebpackPlugin({
title: '<<app>>',
template: 'main.html',
minify: {
collapseWhitespace: false,
removeComments: true,
useShortDoctype: false
}
}),
new MiniCssExtractPlugin({
filename: 'style.[contenthash].css'
}),
new CopyPlugin([
{
from: 'public',
to: 'public'
}
]),
new ProgressBarPlugin({
format: ' build [:bar] ' + ':percent' + ' (:elapsed seconds)' + ' :msg'
}),
new reactLoadablePlugin({
filename: './react-loadable.json'
}),
new workboxPlugin.InjectManifest({
swSrc: path.join(__dirname, '../../public/service-worker.js')
})
],
devServer: {
contentBase: path.join(__dirname, '/'),
filename: 'main.html',
compress: true,
port: 3000,
historyApiFallback: true,
disableHostCheck: true,
useLocalIp: true,
host: '0.0.0.0'
},
devtool: 'eval-source-map'
});

The problem was with the webpack file I was exporting the webpack configurations as a function.
Earlier:
module.exports = (env) => ({
....your webpack configurations
})
Instead of exporting everything as a function I exported it as
Now:
module.exports = {
....your webpack configurations
}
But can someone tell me why the earlier implementation didnt work?

Related

Webpack 5 devserver doesnt recompile on file change

I'm new to Webpack configuration and having trouble setting it up and stuck on it for weeks.
I've got it to compile on start but it doesn't rebuild/recompile on changes.
I've tried to preserve log in browser console and when I save changes, it displays:
[webpack-dev-server] "src/components/Login.jsx" from static directory was changed. Reloading...
But since the code hasnt recompiled, theres no changes on the web.
If anyone can assist please.
I'm using:
NPM 6.14.17
Node v18.14.0
"webpack": "^5.47.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.9.3"
Script> "start": "webpack serve --env type=local"
webpack.config.js
const path = require("path");
// const moment = require('moment');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require ("html-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
let mode = "development";
let target = "web";
if (process.env.NODE_ENV === "production") {
mode = "production";
target = "browserslist";
}
const port = process.env.PORT || 3000;
module.exports = (env) => {
console.log("Passing env", env);
console.log("Target", target);
return {
mode,
stats: "normal",
optimization: {
usedExports: true, //providedExports enabled by default (only used exports are generated for each module)
},
target,
entry: './src/index.js',
output: {
filename: 'bundle.[fullhash].js',
path: path.resolve(__dirname, "dist"),
assetModuleFilename: "images/[hash][ext][query]",
publicPath: '/',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: "asset",
// loader: 'file-loader',
// type: "asset/resource",
// type: "asset/inline",
// parser: {
// dataUrlCondition: {
// maxSize: 8 * 1024,
// }
// }
},
// {
// test: /\.(s[ac]|c)ss$/i,
// use: [
// {
// loader: MiniCssExtractPlugin.loader,
// options: { publicPath: "" }
// },
// "css-loader",
// "postcss-loader",
// "sass-loader"
// ]
// },
{
test: /\.css/,
use: [
"style-loader",
"css-loader",
],
},
{
test: /\.(sass|scss)$/,
use: [{
loader: 'style-loader', // creates style nodes from JS strings
// options: { minimize: env.type == 'live' },
}, {
loader: 'css-loader', // translates CSS into CommonJS
// options: { minimize: env.type === 'live' },
}, {
loader: 'sass-loader', // compiles Sass to CSS
// options: { minimize: env.type === 'live' },
}],
},
]
},
plugins: [
// new CleanWebpackPlugin(),
// new MiniCssExtractPlugin(),
new HtmlWebpackPlugin({
template: "./src/index.html",
// favicon: 'public/favicon.ico',
}),
new BundleAnalyzerPlugin({
analyzerMode: process.env.STATS || "disabled"
}),
],
resolve: {
extensions: [".js", ".jsx"],
},
devtool: 'source-map',
devServer: {
host: 'localhost',
port: port,
liveReload: true,
watchFiles: {
paths: ['src/**/*.jsx', 'public/**/*'],
options: {
usePolling: true,
},
},
static: [
// Simple example
path.resolve(__dirname, 'static'),
// Complex example
{
directory: path.resolve(__dirname, 'static'),
staticOptions: {},
// Don't be confused with `dev.publicPath`, it is `publicPath` for static directory
// Can be:
// publicPath: ['/static-public-path-one/', '/static-public-path-two/'],
publicPath: '/static-public-path/',
// Can be:
// serveIndex: {} (options for the `serveIndex` option you can find https://github.com/expressjs/serve-index)
serveIndex: true,
// Can be:
// watch: {} (options for the `watch` option you can find https://github.com/paulmillr/chokidar)
watch: true,
},
],
hot: true,
historyApiFallback: true,
}
}
}
I've tried looking online for answers and trying different settings but haven't had much luck.
Also tried setting Hot to false but didnt work

Webpack 5, Server-Side rendering, and FOUC

I'm upgrading an existing web site from Webpack 3 to Webpack 5.
The site uses server side rendering for the first load, the client side routing for any in-site navigation. All this worked fine with Webpack 3, but after migrating to Webpack 5 it looks like some of the styles are being applied via javascript and that's creating a FOUC during the first load (after that, in-site navigation works fine and looks correct). As a test, I turned off javascript in my browser; the old site loads fine and looks correct, but the upgraded site does not. It feels like I need style-loader in the server config somewhere, but when that's added, I get a "Cannot GET /" when trying to load the site. Any help is appreciated.
Server-side config
require('dotenv').config({ silent: true });
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const includePaths = [path.resolve(__dirname, 'stylesheets')];
module.exports = {
bail: true,
entry: {
main: './src/entry-server',
},
output: {
path: path.join(__dirname, 'build', 'prerender'),
filename: '[name].js',
publicPath: '/bundle/',
libraryTarget: 'commonjs2',
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
PRERENDER: true,
ASSETS_CDN_PREFIX: JSON.stringify(process.env.ASSETS_CDN_PREFIX || ''),
},
}),
// only load moment english locale: https://github.com/moment/moment/issues/2517
new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en)$/),
new webpack.optimize.ModuleConcatenationPlugin(),
new MiniCssExtractPlugin({
ignoreOrder: true,
}),
],
module: {
rules: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
use: 'babel-loader',
},
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
},
},
'postcss-loader',
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths,
data: `$assetprefix: "${process.env.ASSETS_CDN_PREFIX || ''}";`,
},
},
},
],
},
{
test: /\.svg$/,
use: `svg-inline-loader?removeTags&removingTags[]=${['defs', 'style', 'title'].join(',removingTags[]=')}`,
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss', '.json'],
},
target: 'node',
};
Server entry point
export default function (req, res, environmentConstants, callback) {
// ...setup
match({ routes, location: targetUrl }, (error, redirectLocation, renderProps) => {
// ...setup
fetchSomeData().then(() => renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>,
))
.then((content) => {
callback(null, {
helmet: Helmet.renderStatic(),
content,
initialState: serialize(store.getState(), { isJSON: true }),
env: serialize(someEnvConstants),
});
})
Client-side config
require('dotenv').config({ silent: true });
const AssetsPlugin = require('assets-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const includePaths = [path.resolve(__dirname, 'stylesheets')];
// Match all routes that we want to lazy load
const lazyRouteRegex = /route\/([^/]+\/?[^/]+)Route.jsx$/;
module.exports = {
bail: true,
entry: {
main: './src/entry-client',
vendor: [
'react',
'react-dom',
'react-router',
'redux',
'react-redux',
'xmldom',
],
},
output: {
path: path.join(__dirname, 'build', 'public', '[fullhash]'),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
publicPath: `${process.env.ASSETS_CDN_PREFIX || ''}/build/public/[fullhash]/`,
},
plugins: [
// only load moment english locale: https://github.com/moment/moment/issues/2517
new webpack.ContextReplacementPlugin(/moment[\\/]locale$/, /^\.\/(en)$/),
new MiniCssExtractPlugin({
ignoreOrder: true,
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
PRERENDER: false,
ASSETS_CDN_PREFIX: JSON.stringify(process.env.ASSETS_CDN_PREFIX || ''),
},
}),
new AssetsPlugin(),
new CleanPlugin([path.join(__dirname, 'build', 'public')]),
new CompressionPlugin(),
// new BundleAnalyzerPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
exclude: lazyRouteRegex,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: lazyRouteRegex,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'bundle-loader',
options: {
lazy: true,
},
},
{
loader: 'babel-loader',
},
],
},
{
test: /swiper.*\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: false,
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths,
data: `$assetprefix: "${process.env.ASSETS_CDN_PREFIX || ''}";`,
},
},
},
],
},
{
test: /\.s?css$/,
exclude: /swiper.*\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
},
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths,
data: `$assetprefix: "${process.env.ASSETS_CDN_PREFIX || ''}";`,
},
},
},
],
},
{
test: /\.svg$/,
use: `svg-inline-loader?removeTags&removingTags[]=${['defs', 'style', 'title'].join(',removingTags[]=')}`,
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.css', '.scss', '.json'],
},
target: 'web',
};

In react, Websocket connection failed error in react after installed webpack and deploy to DigitalOcean

Here is my webpack config:
webpack.common.js
const { ContextReplacementPlugin, IgnorePlugin } = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const path = require('path');
const babelOptions = {
babelrc: true,
extends: path.join(__dirname, '/.babelrc'),
cacheDirectory: true,
};
module.exports = {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/',
assetModuleFilename: '[path][contenthash][ext]',
},
stats: {
all: false,
modules: true,
errors: true,
warnings: true,
moduleTrace: true,
errorDetails: true,
performance: true,
reasons: true,
assets: true,
assetsSort: 'size',
usedExports: true,
},
resolve: {
extensions: [
'.webpack.js',
'.web.js',
'.mjs',
'.js',
'.jsx',
'.json',
'.ts',
'.tsx',
],
alias: {
// assets: path.resolve(__dirname, 'src/assets'),
react: path.resolve('./node_modules/react'),
},
},
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto',
},
{
test: /\.mp4$/,
use: 'file-loader?name=videos/[name].[ext]',
},
{
test: /\.(jpe?g|png|gif|svg)$/,
type: 'asset',
parser: {
dataUrlCondition: {
// Inline files smaller than 10 kB (10240 bytes)
maxSize: 10 * 1024,
},
},
use: [
{
loader: 'image-webpack-loader',
options: {
name: '[path][contenthash].[ext]',
},
},
],
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: babelOptions,
},
{
loader: 'ts-loader',
options: { transpileOnly: true },
},
],
},
{
test: /\.jsx?$/,
exclude: /node_modules\/(?!(kdbush|supercluster)\/).*/,
use: [
{
loader: 'babel-loader',
options: babelOptions,
},
],
},
{
test: /\.js$/,
use: 'source-map-loader',
enforce: 'pre',
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
// favicon: './public/favicon.ico',
// filename: 'index.html',
// manifest: './public/manifest.json',
}),
new ContextReplacementPlugin(/\/ethers\//, (data) => {
delete data.dependencies[0].critical;
return data;
}),
new NodePolyfillPlugin({
excludeAliases: ['console'],
}),
new ForkTsCheckerWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{
from: path.resolve(__dirname, 'public/favicon.ico'),
to: path.resolve(__dirname, 'build/favicon.ico'),
},
{
from: path.resolve(__dirname, 'public/manifest.json'),
to: path.resolve(__dirname, 'build/manifest.json'),
},
],
}),
],
ignoreWarnings: [/Failed to parse source map/],
devServer: {
historyApiFallback: true,
client: {
webSocketURL: 'ws://0.0.0.0:8080/ws',
},
},
};
webpack.prod.js
const CompressionPlugin = require('compression-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { merge } = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const ClosurePlugin = require('closure-webpack-plugin');
const webpack = require('webpack');
const Dotenv = require('dotenv-webpack');
const common = require('./webpack.common');
require('dotenv').config();
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
output: { filename: 'js/[name].[contenthash].js' },
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'resolve-url-loader',
'sass-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles/[name].[contenthash].css',
chunkFilename: 'styles/[id].[contenthash].css',
}),
new Dotenv({ systemvars: true }),
new CompressionPlugin({
filename: '[path][base].gz[query]',
test: /\.(js|css)$/,
algorithm: 'gzip',
compressionOptions: {
level: 9,
},
}),
new CompressionPlugin({
filename: '[path][base].br[query]',
test: /\.(js|css)$/,
algorithm: 'brotliCompress',
compressionOptions: {
level: 11,
},
}),
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const nodeModulePath = module.context.match(
/[\\/]node_modules[\\/](.*?)([\\/]|$)/
);
if (nodeModulePath) {
const packageName = nodeModulePath[1];
// npm package names are URL-safe, but some servers don't like # symbols
return `npm.${packageName.replace('#', '')}`;
}
},
},
},
},
minimizer: [
new TerserPlugin(),
new CssMinimizerPlugin(),
new ClosurePlugin({ mode: 'STANDARD' }, {}),
],
},
devServer: { allowedHosts: 'all' },
});
The error is
Error Message in chrome devTool
This project is working in my local. Not working after deployment to digitalOcean.
I think the websocket port has the problem.
To fix this, how can I config webpack for production?
Please let me know your thought.
Thanks!

how to reduce main.js and main.css and vendor.js divide in small chunk using webpack in react js?

I am working on performance optimization in react site last few days and I have read code-splitting documents using webpack. I have small knowledge about webpack bundling and code splitting. my webpack code.
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; // eslint-disable-line prefer-destructuring
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const DuplicatePackageCheckerPlugin = require("duplicate-package-checker-webpack-plugin");
const CompressionPlugin = require('compression-webpack-plugin'); //gzip
const BrotliPlugin = require('brotli-webpack-plugin'); //brotli
const CopyWebpackPlugin = require('copy-webpack-plugin');
const config = require('config');
const webpackConfig = {
mode: config.get('webpack.mode'),
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, config.get('webpack.output.path')),
filename: `${config.get('webpack.output.scripts')}/[name].[hash:8].js`,
chunkFilename: `${config.get('webpack.output.scripts')}/[name].[chunkhash:8].js`,
publicPath: config.get('webpack.publicPath'),
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: [
{
loader: 'babel-loader',
},
],
exclude: /node_modules/,
},
{ // config for sass compilation
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
{
loader: "sass-loader"
}
]
},
{ // config for images
test: /\.(png|svg|jpg|jpeg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images',
}
}
],
},
{ // config for fonts
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts',
}
}
],
},
],
},
plugins: [
(config.get('webpack.mode') === 'production') ? new CleanWebpackPlugin([
config.get('webpack.output.path'),
]) : () => {},
(config.get('webpack.mode') === 'production') ? new DuplicatePackageCheckerPlugin() : () => {},
(config.get('webpack.mode') === 'production') ?(
new CompressionPlugin({ //gzip plugin
filename: '[path].gz[query]',
algorithm: 'gzip',
test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif|png|jpg)$/,
threshold: 8192,
minRatio: 0.8
}),
new BrotliPlugin({ //brotli plugin
asset: '[path].br[query]',
test: /\.(js|css|html|svg|txt|eot|otf|ttf|gif|png|jpg)$/, //(js|css|html|svg|txt|eot|otf|ttf|gif)$/
threshold: 10240,
minRatio: 0.6
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'public' }
]
})
):()=>{},
new HTMLWebpackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
}),
new MiniCssExtractPlugin({
filename: `${config.get('webpack.output.styles')}/[name].[chunkhash:8].css`,
chunkFilename: `${config.get('webpack.output.styles')}/[name].[chunkhash:8].css`,
}),
new CaseSensitivePathsPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: process.env.BA_MODE ? process.env.BA_MODE : 'disabled',
}),
],
optimization: {
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
minSize: 0,
name: config.get('webpack.vendorsCodeSplitting') ? (module) => {
const re = /[\\/]node_modules[\\/](.*?)([\\/]|$)/;
const packageName = module.context.match(re)[1];
return `vendors/pkg.${packageName.replace('#', '')}`;
} : 'vendors',
priority: -10,
},
default: {
name: 'default',
minChunks: 2,
reuseExistingChunk: true,
enforce: true,
priority: -20,
},
},
},
minimizer: [
(config.get('webpack.uglify')) ? new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: !!config.get('webpack.sourcemap'),
}) : () => {},
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: [
'default', {
discardComments: {
removeAll: true,
},
},
],
},
}),
],
},
devtool: config.get('webpack.sourcemap'),
devServer: {
contentBase: path.resolve(__dirname, 'public'),
historyApiFallback: true,
publicPath: config.get('webpack.publicPath'),
open: config.get('webpack.open'),
overlay: true,
},
};
module.exports = webpackConfig;
I don't know what I am doing wrong with webpack configuration to improve Google page insight speed index. I also attached a screenshot bundle analysis. many third-party libraries use on a home page its impacts on page speed? thank in advanced

React errors showing in console but not window

When I work with a CRA app, and most React Apps, an error in the code will cause the browser to show an error screen instead of the application.
The legacy code I'm working on doesn't do this. An error that basically crashes the app just shows a blank screen (black screen, which I imagine is our background color), and you only know what's going on by opening the dev console for the browser.
The project was made with CRA, but quite a while ago. It does not include react-scripts anywhere.
How do I set this back to "normal" so that the errors will show in the browser window itself?
This is my current webpack config
const os = require('os');
const path = require('path');
const ip = require('my-local-ip');
const colors = require('colors');
const process = require('process');
const webpack = require('webpack');
const states = require('./util/state-spoof');
const childProcess = require('child_process');
const PlayerIdPlugin = require('./plugins/PlayerIdPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const MiniCssExtractPlugin = require('extract-css-chunks-webpack-plugin');
const envPort = process.env.PORT;
const port = envPort ? envPort : 3000;
const spoof = states[process.env.SPOOF || 'NH'];
const forcedProdAPI = process.env.FORCE_PROD_API || false;
const platform = os.platform().toLowerCase();
const isLinux = platform === 'linux';
const isWindows = platform === 'win32' || platform === 'win64';
if (!process.env.NODE_ENV) process.env.NODE_ENV = 'development';
const mode = process.env.NODE_ENV;
const sessionKey = process.env.SESSION_KEY || '';
const linter = {
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: path.resolve(__dirname, 'src'),
};
const imgLoad = {
test: /\.(gif|png|jpe?g)$/i,
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
};
const jsLoad = {
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
},
exclude: /(node_modules)/,
};
const tsLoad = {
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
};
const sassLoad = {
test: /\.s?(a|c)ss$/,
use: [
mode.includes('dev') ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
const fileLoad = {
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
};
module.exports = {
mode: mode,
stats: 'errors-only',
entry: './src/browser/index.js',
output: {
path: path.resolve(__dirname, '..', 'src', 'public'),
filename: 'static/scripts/bundle.js',
publicPath: '/',
},
module: {
rules: [
linter,
{ oneOf: [imgLoad, jsLoad, tsLoad, sassLoad, fileLoad] },
],
},
plugins: [
new PlayerIdPlugin({
output: path.resolve(
__dirname, '..', 'src', 'browser', 'services', 'PlayerIDHelper.js'
),
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(mode),
'process.env.FORCE_PROD_API': JSON.stringify(forcedProdAPI),
'process.env.SESSION_KEY': JSON.stringify(sessionKey),
'process.env.NERF_THIRD_PARTY': 'false',
'process.env.BROWSER': 'true',
'process.env.SPOOF': JSON.stringify(spoof),
}),
new MiniCssExtractPlugin({
filename: 'static/styles/main.css',
}),
new webpack.HotModuleReplacementPlugin(),
],
devtool: 'inline-source-map',
devServer: {
hot: true,
host: '0.0.0.0',
port: port,
disableHostCheck: true,
quiet: true,
compress: true,
contentBase: path.resolve(__dirname, '..', 'src', 'public'),
historyApiFallback: true,
before: () => {
console.log(
colors.bold.white(
`Server currently listening :\n`
) +
colors.reset.yellow(
`\nMachine access: http://localhost:${port}\n`
) +
colors.reset.yellow(
`Network access: http://${ip()}:${port}`
)
);
if (!isLinux && !isWindows) {
childProcess.execSync('ps cax | grep "Google Chrome"');
childProcess.execSync(
`osascript chrome.applescript "${encodeURI(
`http://localhost:${port}`
)}"`,
{
cwd: path.resolve(__dirname),
stdio: 'ignore',
}
);
}
},
},
};

Resources