ReactJS Webpack : ReferenceError: window is not defined - reactjs

I'm using webpack in React JS. and Here is my error,
ERROR in Error: /Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:58758
var theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
^
ReferenceError: window is not defined
src:58758 Object../node_modules/react-axe/dist/index.js
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:58758:13
src:113496 webpack_require
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:113496:42
src:38954 Module../node_modules/html-webpack-plugin/lib/loader.js!./src/index.js
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:38954:13
src:113496 webpack_require
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:113496:42
src:113646
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:113646:18
src:113647
/Users/prakash/Desktop/projects/limitscale/goal.ly/goaly-react/src:113647:12
index.js:321 HtmlWebpackPlugin.evaluateCompilationResult
[goaly-react]/[html-webpack-plugin]/index.js:321:28
index.js:237
[goaly-react]/[html-webpack-plugin]/index.js:237:22
task_queues.js:93 processTicksAndRejections
internal/process/task_queues.js:93:5
and my webpack config file,
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ROOT_DIRECTORY = path.join(__dirname, '..')
const SRC_DIRECTORY = path.join(ROOT_DIRECTORY, 'src')
const devMode = process.env.NODE_ENV !== 'production';
const plugins = [];
plugins.push(new HtmlWebpackPlugin({
template: path.join(SRC_DIRECTORY, '')
})
);
plugins.push( new CopyWebpackPlugin({
patterns: [
{ from: path.join(SRC_DIRECTORY, 'assets'), to: path.join(ROOT_DIRECTORY, 'build') }
],
}));
plugins.push(new MiniCssExtractPlugin())
const config = {
entry: [path.resolve(__dirname, '../src/index.js')],
output: {
globalObject: "this",
path: path.resolve(__dirname, '../build'),
// filename: 'bundle.js',
filename: '[name].[hash:8].js',
sourceMapFilename: '[name].[hash:8].map',
chunkFilename: '[id].[hash:8].js',
publicPath: '/',
},
mode: 'development',
resolve: {
modules: [path.resolve('node_modules'), 'node_modules'],
extensions: [".jsx", ".js"]
},
performance: {
hints: false
},
plugins: plugins ,
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(jpe?g|gif|bmp|mp3|mp4|ogg|wav|eot|ttf|woff|woff2|png|svg)$/,
use: ['url-loader?limit=10000']
}
]
}
}
module.exports = config
What should I do to avoid this error?
Facing this issue for a while. Couldn't able to figure out. Is there any error in my code?.New to 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')
})
]
}

Webpack5 config error: An appropriate loader to handle this file type

I'm trying to migrate webpack4 to webpack5. My project has both react and typescript files.
I'm running into below error:
ERROR in ./src/index.js 19:4
Module parse failed: Unexpected token (19:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
>ReactDOM.render(
> > <Provider store={store}>
> | <App/>
> | </Provider>
,
webpack 5.11.1 compiled with 1 error in 67 ms
webpack.common.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const moment = require('moment');
const CircularDependencyPlugin = require('circular-dependency-plugin');
module.exports = (...args) => {
const [
env,
{ configName }
] = args;
return {
entry: ['#babel/polyfill', './src/index.js'],
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: './index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[name].[chunkhash].css',
}),
new webpack.DefinePlugin({
__SNAPSHOT__: JSON.stringify(moment().format('MMMM Do YYYY, h:mm:ss a')),
__MODE__: JSON.stringify(env),
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: true,
allowAsyncCycles: false,
cwd: process.cwd(),
})
],
output: {
path: path.resolve(__dirname, 'build'),
chunkFilename: '[name].[chunkhash].js',
filename: '[name]_bundle.js',
publicPath: '/build/',
chunkLoading: false
},
target: ['web'],
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript",
],
},
},
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.(sa|sc)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: env === 'development',
},
},
'css-loader',
'postcss-loader',
'sass-loader',
]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['url-loader']
}
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
port: 8888
}
}
};
try it removing:
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},

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

Webpack - "css-loader/locals" miss matched for server.build and client.build

I setup a webpack config to build server.build and client.build, but they both producing different css/locals.
webpack.server.js
const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const serverConfig = {
name: 'server',
target: 'node',
externals: [nodeExternals()],
entry: [
__dirname+'/index.js'
],
output: {
path: path.join(__dirname, '/.build'),
filename: 'server.build.js',
publicPath: '.build/',
libraryTarget: 'commonjs2'
},
module: {
loaders: [
{
test:/\.(?:js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(?:css|less)$/,
use: "css-loader/locals?import=1&modules=1&localIdentName=[name]__[local]__[hash:base64:7]",
exclude: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/,
loader: 'url-loader?limit=1000&name=./fonts/[name].[ext]?[hash:base64:5]#icomoon',
}
]
},
resolve: {
extensions: ['.jsx', '.js', '.json','.less']
}
};
module.exports = serverConfig;
webpack.client.js
const webpack = require('webpack');
const path = require('path');
const context = path.resolve(__dirname, 'src');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
name:"client",
context,
entry: __dirname+'/src/app.js',
output: {
path: __dirname+"/.build/assets",
filename: 'bundle.js'
},
devtool: "source-map",
module: {
rules: [
{
test:/\.(?:js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(?:css|less)$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader?module',
options: {
sourceMap: true,
importLoader: true,
localIdentName:'[name]__[local]__[hash:base64:7]'
}
},
{
loader: 'less-loader',
options: {
sourceMap: true,
importLoader: true,
}
}
],
fallback: 'style-loader',
}),
exclude: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?[\s\S]+)?$/,
loader: 'url-loader?limit=1000&name=./fonts/[name].[ext]?[hash:base64:5]#icomoon',
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'bundle.css',
allChunks: true,
}),
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true),
NODE_ENV: JSON.stringify("production")
}
}),
],
resolve: {
extensions: ['.jsx', '.js', '.json']
}
};
module.exports = config;
Ex: server.build.js -> style__cont__2KTI-wF
bundle.js/bundle.css (client) -> style__cont__58B3ts_
I am really stuck at this point, i am new to react and there is no perfect approach to import css server side.

Resources