react webpack breaks when i import - javascript

so I'm having a lot of trouble configuring webpack on a react app that I have to setup from scratch. The issue is that when I import axios in my App.js webpack fails without any errors, it says that it was compiled successfully but only serves the bare index.html and if I just comment out the axios import line it goes back to normal here's my code bellow:
App.js
import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
//import axios from 'axios'
import Login from './Components/Login'
import Test from './Components/Test'
import './Styles/App.css'
const App = () => {
const [user, setUser] = React.useState(true)
const isUserValid = () => {
}
return (
<div className="app">
<Router>
{!user ? (
<Login />
) : (
<>
<div className="app__body">
<Switch>
<Route path="/"><Test /></Route>
</Switch>
</div>
</>
)}
</Router>
</div>
);
};
export default App;
package.json
{
"name": "project",
"version": "1.0.0",
"description": "base react app",
"main": "index.js",
"scripts": {
"start": "webpack serve --hot --open --mode development --client-logging verbose",
"build": "webpack --mode=production"
},
"author": "",
"license": "ISC",
"dependencies": {
"#hookform/resolvers": "^2.8.2",
"#material-ui/core": "^4.12.3",
"axios": "^0.23.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.17.5",
"react-router-dom": "^5.3.0",
"yup": "^0.32.11"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/plugin-transform-runtime": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"css-loader": "^6.4.0",
"css-minimizer-webpack-plugin": "^3.1.1",
"eslint-webpack-plugin": "^3.0.1",
"html-webpack-plugin": "^5.4.0",
"mini-css-extract-plugin": "^2.4.3",
"style-loader": "^3.3.0",
"webpack": "^5.58.2",
"webpack-cli": "^4.9.0",
"webpack-dev-server": "^4.3.1"
}
}
webpack.config.js
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
devServer: {
client: {
logging: 'info',
},
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
},
extensions: ["*", ".js", ".jsx", ".scss"],
fallback: {
assert: false,
http: false,
https: false,
zlib: false,
tty: false,
util: false,
fs: false,
net: false,
stream: false
}
},
target: "web",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: { loader: 'babel-loader', },
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: ['file-loader']
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/styles.css',
}),
new HtmlWebPackPlugin({
template: './public/index.html',
}),
],
};
I really would aprreciate if anyone could help solve this problem it's been driving me crazy.

Related

Ant Design Icon Not Show

I Cant Use Icon In Ant Design.
I searched a lot but the solutions I found did not solve the problem.
i Import Icon And Css And Update Ant Design To Last Version But Get Error:
Warning: [#ant-design/icons] icon should be icon definiton, but got /4f46ee92ada510e371cc67531388e94e.js
My Code:
import React from "react";
import 'antd/dist/antd.css';
import { CheckCircleTwoTone, HeartTwoTone, SmileTwoTone } from '#ant-design/icons';
import { Space } from 'antd';
class App extends React.Component{
render() {
return (
<>
<Space>
<SmileTwoTone />
<HeartTwoTone twoToneColor="#eb2f96" />
<CheckCircleTwoTone twoToneColor="#52c41a" />
</Space>
</>
)
}
}
export default App;
Package.json
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve --hot --open",
"build": "webpack --config webpack.config.js --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#ant-design/icons": "^4.7.0",
"antd": "^4.22.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0"
},
"devDependencies": {
"#babel/core": "^7.18.10",
"#babel/preset-env": "^7.18.10",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.0"
}
}
webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.[hash].js",
path: path.resolve(__dirname, "dist"),
publicPath: '/'
},
mode: 'development',
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
resolve: {
modules: [__dirname, "src", "node_modules"],
extensions: ["*", ".js", ".jsx", ".tsx", ".ts"],
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: require.resolve("babel-loader"),
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.png|svg|jpg|gif$/,
use: ["file-loader"],
},
],
},
devServer: {
historyApiFallback: true,
},
};

Webpack: How to rewrie URL in .css

For 3 days straight I am having a trouble to setup Webpack for staging purposes.
The goal is to rewrite url of assets in final .css file (frontend.css) like this:
Let's say that in .scss file I have:
background: url('/assets/image.png') (this works for dev and prod)
and in final outputted .css file for staging, I want it to be:
background: url('https://stage.domain.com/staging/project-name/assets/image.png')
I have script npm run stage, that build js. and .css only for staging puposes.
It creates stage dir on root with two files frontened-bundle.js and frontend.css. (see bottom of "Files structure" screenshot).
I tried to rewrite url with resolve-url-loader with root parameter, but I cant get it working.
publicPath is also ignored.
I am not sure what I am doing wrong.
Please point me in right direction.
Files structure:
webpack.stage.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const public_path = 'https://stage.domain.com/staging/project-name/'
module.exports = {
context: __dirname,
entry: {
frontend: [
'./src/js/index.js',
'./src/scss/main.scss'
],
// customizer: './src/customizer.js'
},
resolve: {
extensions: ['.ts', '.js', '.jsx', '.scss', '...',],
},
output: {
path: path.resolve(__dirname, 'stage'),
publicPath: public_path,
filename: '[name]-bundle.js'
},
mode: 'production',
// devtool: 'cheap-eval-source-map',
module: {
rules: [
{
enforce: 'pre',
exclude: /node_modules/,
test: /\.jsx$/,
loader: 'eslint-loader'
},
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: public_path,
sourceMap: true
}
},
{
loader: 'css-loader',
options: {
url: false,
sourceMap: true
}
},
{
loader: 'resolve-url-loader',
options: {
// root: path.join(__dirname, './'), // returns url("../../assets/assets/fonts/NewYork.woff2")
// root: '/', // returns url('../../../../../../assets/fonts/NewYork.woff2')
// root: './', // returns url('../../assets/fonts/NewYork.woff2')
attempts: 1,
debug: true,
sourceMap: true,
publicPath: public_path,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
},
]
},
{
test: /\.(ttf|woff|woff2|eot|jpe?g|png|svg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
// outputPath: '../',
publicPath: publicPath,
},
},
'img-loader',
'url-loader',
]
}
]
},
plugins: [
// new StyleLintPlugin(),
new MiniCssExtractPlugin({
filename: '[name].css'
}),
],
optimization: {
// minimizer: [new UglifyJsPlugin(), new OptimizeCssAssetsPlugin()]
}
};
package.json
{
"name": "project_name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode=production",
"dev": "webpack --watch",
"stage": "npm run clean && webpack --config webpack.stage.js -p --progress --profile",
"clean": "rm -rf stage"
},
"repository": {
"type": "git",
"url": ""
},
"keywords": [
"webpack"
],
"author": "",
"license": "ISC",
"bugs": {
"url": ""
},
"homepage": "",
"devDependencies": {
"#babel/cli": "^7.14.5",
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"autoprefixer": "^9.6.4",
"babel-eslint": "^10.0.3",
"babel-loader": "^8.0.6",
"browser-sync": "^2.27.4",
"browser-sync-webpack-plugin": "^2.2.2",
"css-loader": "^3.2.0",
"css-mqpacker": "^7.0.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"eslint-config-wordpress": "^2.0.0",
"eslint-loader": "^3.0.2",
"eslint-plugin-prettier": "^3.1.1",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"img-loader": "^3.0.1",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.14.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"prettier": "^1.18.2",
"resolve-url-loader": "^4.0.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"stylelint": "^11.0.0",
"stylelint-config-recommended-scss": "^4.0.0",
"stylelint-config-wordpress": "^15.0.0",
"stylelint-order": "^3.1.1",
"stylelint-scss": "^3.11.1",
"stylelint-webpack-plugin": "^1.0.1",
"svg-sprite-loader": "^4.1.6",
"svgo": "^1.3.0",
"svgo-loader": "^2.2.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"url-loader": "^4.1.1",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9",
"wp-pot-cli": "^1.5.0"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"imagemin": "^8.0.0",
"jquery": "^3.6.0"
}
}
I've had this similar issue in the past, I tried the below from the docs,
const ASSET_PATH = process.env.ASSET_PATH || '/';
export default {
output: {
publicPath: ASSET_PATH,
},
plugins: [
// This makes it possible for us to safely use env vars on our code
new webpack.DefinePlugin({
'process.env.ASSET_PATH': JSON.stringify(ASSET_PATH),
}),
],
};
But actually, the one that worked perfectly for my issue is below, while the public path was the CDN link from where the assets were served
require('dotenv').config();
__webpack_public_path__ = config.publicPath // publicPath is process.env.ASSET_PATH || '/';
When you set the publicPath as "../" did you also try the useRelativePaths: true?
Ref:- https://github.com/webpack-contrib/file-loader#userelativepath

Integrate React 17 with webpack 5 and babel-plugin-react-css-modules (css modules with stylename)

I am trying to setup a react app with latest versions.
React 17, Webpack 5 and other modules.
I need css modules with styleName concept by using babel-plugin-react-css-modules
Trying to run the code shows the output but no styles are applied.
package.json
{
"name": "react-app",
"version": "1.0.0",
"description": "React Template App",
"author": "",
"license": "ISC",
"main": "index.js",
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production",
"format": "prettier --write \"src/**/*.js\"",
"eslint-fix": "eslint --fix \"src/**/*.js\""
},
"dependencies": {
"babel-plugin-react-css-modules": "^5.2.6",
"react": "^17.0.1",
"react-dom": "^17.0.1"
},
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-eslint": "^10.1.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.1",
"eslint": "^7.16.0",
"eslint-config-react": "^1.1.7",
"eslint-loader": "^4.0.2",
"eslint-plugin-react": "^7.21.5",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.0",
"less": "^4.0.0",
"less-loader": "^7.2.0",
"mini-css-extract-plugin": "^1.3.3",
"prettier": "2.2.1",
"style-loader": "^2.0.0",
"webpack": "^5.11.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname, "dist"),
open: true,
host: "localhost",
compress: true,
port: process.env.CLIENT_PORT,
hot: true,
quiet: false
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.css$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
// "less-loader",
{
loader: 'css-loader',
options: {
modules: true,
}
}
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html",
filename: "./index.html",
favicon: "./public/favicon.ico"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
devtool: 'inline-source-map',
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
home.js
import React from "react";
import "./style.css";
const Home = () => {
return (
<div styleName="container">
<div styleName="title">Hello from Home CSS</div>
</div>
);
};
export default Home;
style.css
.container {
display: flex;
flex-direction: column;
}
.title {
font-size: 24px;
color: red;
}
That's interesting issue which requires us to do a few more things to make it work as following:
babel-plugin-react-css-modules isn't working properly with css-loader in case of generating the name. But luckily we have a work around by using a temporary fix of someone #dr.pogodin/babel-plugin-react-css-modules. So just install needed packages:
npm i -D #dr.pogodin/babel-plugin-react-css-modules postcss // postcss is required aslo
Reconfigure babel configuration by changing the name in .babelrc:
{
// ...
"plugins": [
[
"#dr.pogodin/babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}
]
]
}
Finally, we would change the class name to make it consistent between babel-plugin-react-css-modules and css-loader in webpack.config.js:
{
test: /\.css$/,
use: [
// ...
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[path]___[name]__[local]___[hash:base64:5]', // This pattern matches with the default in `babel-plugin-react-css-modules`
},
}
}
],
}

webpack PurgeCSS webpack Plugin not working as expected

I want to purge unused CSS from the Clarity UI CSS file, in a setup using webpack and purgecss-webpack-plugin.
However, while the size of the CSS file is reduced from 565kB to 172kB, it should be reduced to 0kB since I don't use any of it. If I do the same thing using Bootstrap, the filesize is reduced to 1kB.
Why is that behaviour and is there a fix?
My folder structure is as follows:
|-dist
|
|-node_modules
|
|-src
|--index.js
|
|.babelrc
|package.json
|webpack.config.js
My package.json:
{
"name": "webpack-clarity",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"start": "node ./index.js",
"build": "webpack"
},
"dependencies": {
"#clr/ui": "^4.0.0",
"bootstrap": "^4.5.2"
},
"devDependencies": {
"#babel/core": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"babel-loader": "^8.1.0",
"css-loader": "^3.6.0",
"glob": "^7.1.6",
"html-webpack-plugin": "^4.3.0",
"mini-css-extract-plugin": "^0.9.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"purgecss-webpack-plugin": "^2.3.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const glob = require("glob");
const PurgeCSSPlugin = require("purgecss-webpack-plugin");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
optimization: {
minimizer: [new OptimizeCssAssetsPlugin(), new TerserPlugin()],
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: "[name].css" }),
new PurgeCSSPlugin({
paths: glob.sync("./src/**/*.js", { nodir: true }),
}),
],
};
.babelrc
{
"presets": [
[
"#babel/preset-env",
{"modules": false}
]
]
}
index.js
import "../node_modules/#clr/ui/clr-ui.min.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

how to fix warning with React and babel: Parsing error: Unexpected token <

I have this app where I have added react, babel and webpack.
Repo in github: https://github.com/GiorgioMartini/holli
Its seems to work ok, buti get this error:
WARNING in ./src/scripts/index.js
Module Warning (from ./node_modules/eslint-loader/dist/cjs.js):
/Users/giorgio/Documents/frontend-assessment-test/src/scripts/index.js
7:7 error Parsing error: Unexpected token <
✖ 1 problem (1 error, 0 warnings)
that line 7:7 is this one where the div starts after the reurn:
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
render() {
return (
<div>
Hella
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
)
So im guessing its some babel misconfiguration or something.
This is my babel config file:
const Path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: Path.resolve(__dirname, '../src/scripts/index.js')
},
output: {
path: Path.join(__dirname, '../build'),
filename: 'js/[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
name: false
}
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin([
{ from: Path.resolve(__dirname, '../public'), to: 'public' }
]),
new HtmlWebpackPlugin({
template: Path.resolve(__dirname, '../src/index.html')
})
],
resolve: {
alias: {
'~': Path.resolve(__dirname, '../src')
}
},
module: {
rules: [
{ test: /\.(js)$/, use: ['babel-loader', 'eslint-loader'], exclude: /node_modules/},
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]} ]
}
};
And this is the package.json:
"name": "frontend-assessment-test",
"version": "1.0.0",
"description": "A frontend assessment test for our new pirates, which are willing to come on board.",
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack/webpack.config.prod.js --colors",
"start": "webpack-dev-server --open --config webpack/webpack.config.dev.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holidaypirates/frontend-assessment-test"
},
"author": "HolidayPirates",
"license": "MIT",
"bugs": {
"url": "https://github.com/holidaypirates/frontend-assessment-test/issues"
},
"devDependencies": {
"#babel/core": "^7.7.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.7.4",
"#babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"cross-env": "^6.0.3",
"css-loader": "^3.2.0",
"eslint": "^6.7.1",
"eslint-loader": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^4.0.0-beta.11",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"core-js": "^3.3.3",
"react": "^16.12.0",
"react-dom": "^16.12.0"
}
}
Any ideas where could be the issue and how to fix it?
here is the repo: https://github.com/GiorgioMartini/holli
I found the answer,
that is just a eslint error, so the app works fine is just eslint complaining.
I had to add this to the eslintrc file and now its fixed:
"extends": [
"plugin:react/recommended"
]

Categories