Wepack 5 My Components are Not Rendering Properly - reactjs

My Components are not rendering properly on the screen eventhough there are no errors in the console. I think I didnt configure my Webpack 5 well for production. This happens when I type in the terminal "yarn run dev-server" or "npm run serve"
Here are my scripts in package.json:
"scripts": {
"serve": "live-server public/",
"build:dev": "webpack --mode development",
"build:prod": "webpack --mode production --env production",
"dev-server": "webpack serve --mode development --open",
"test": "jest --config=jest.config.json"
},
Here is my webpack file (also not sure if I should separate them into different files):
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env)=>{
const isProduction = env === 'production';
return {
entry: './src/app.js',
output: {
path:path.join(__dirname, 'public'),
filename:'bundle.js'
},
module: {
rules:[{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
// 'style-loader',
],
}]
},
plugins: [new MiniCssExtractPlugin()],
devtool: isProduction ? 'source-map': 'eval-cheap-module-source-map',
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000
},
devServer: {
static: path.join(__dirname, 'public'),
historyApiFallback: true
}
};
};
Please let me know what I need to do.

Related

webpack-dev-server 4 works, but webpack 5 fails to load icon

I am currently using Webpack version 5, Webpack-dev-server version 4, and Salesforce Lightning React Component. The webpack-dev-server can load the static icons successfully, but the webpack one cannot load.
Here is the image with webpack-dev-server version 4:
Webpack-dev-server
Here is the image with webpack version 5:
Webpack
Here is the snapshot of my code using Salesforce React Lightning:
Salesforce React Lightning Component
Here is the folder structure of my project, and the location of my icon files: Project Folder Structure
In Salesforce React Component, they have the IconSettings with iconPath prop which you specify the location of the files, and an array which contain the "name" of the file, and the "category" of the file or the the name of the folder.
Here is my package.json script:
"scripts": {
"start": "webpack serve",
"build": "webpack",
"test": "react-scripts test",
"eject": "react-scripts eject"}
Here is my webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.tsx",
output: { path: path.join(__dirname, "build"), filename: "index.bundle.js" },
mode: process.env.NODE_ENV || "development",
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
devServer: { static: [path.join(__dirname, "src"), path.join(__dirname, "public")], historyApiFallback: true },
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ["ts-loader"],
},
{
test: /\.(css|scss)$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(jpg|jpeg|png|gif|mp3|mp4|ico|svg)$/,
type: "asset/resource"
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "public", "index.html"),
}),
],
};
Here is my .babelrc file:
{
"presets": [
"#babel/env",
"#babel/react",
"#babel/preset-typescript",
"#salesforce/babel-preset-design-system-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
]
}

electron-builder built app doesn't run after build, but works before

I have a project which uses both electron-packager and electron-builder. When I run npm run packaged it is packaged up as .app file into the builds/ folder and there is no issue running the app. When I run npm run build or npm run build:mac, electron-builder successfully builds, signs and creates a .dmg and a .zip file as well as the .app file into the dist/ folder, however the .app file doesn't run as it appears that the src has not compiled correctly and files are missing. I'm sure I'm over looking something in my config but have hit a roadblock.
Here is my package.json:
{
"name": "my-electron-app",
"productName": "ACME Electron",
"version": "0.1.0",
"license": "MIT",
"main": "mainprocess/main.js",
"scripts": {
"start": "react-scripts start",
"clean:build": "rimraf builds",
"clean:dist": "rimraf dist",
"tes": "rimraf archive/tunnel-utils-darwin-x64",
"testDev": "cross-env NODE_ENV=development electron .",
"testProd": "cross-env NODE_ENV=production electron . --noDevServer",
"dev": "webpack-dev-server --progress --hot --host 0.0.0.0 --config=./webpack.dev.config.js",
"build": "npm run clean:dist && webpack --progress --config webpack.build.config.js",
"package": "cross-env NODE_ENV=production npm run clean:dist && webpack --config webpack.build.config.js",
"postpackage": "cross-env NODE_ENV=production npm run clean:build && electron-packager . ${npm_package_productName} --overwrite --icon=assets/icons/mac/icon.icns --prune=true --ignore='(.circleci|archive|assets|build|builds|signing|scaffold|src)' --asar.unpackDir=node_modules/ngrok/* --out=builds",
"package-mac": "cross-env NODE_ENV=production electron-packager . ${npm_package_productName} --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --ignore='(.circleci|archive|assets|build|builds|signing|scaffold|src)' --asar.unpackDir=node_modules/ngrok/* --out=builds",
"package-win": "cross-env NODE_ENV=production electron-packager . ${npm_package_productName} --overwrite --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --asar.unpackDir=node_modules/ngrok/* --out=builds --version-string.CompanyName=ACME --version-string.FileDescription=ACME --version-string.ProductName=\"My App\"",
"package-linux": "cross-env NODE_ENV=production electron-packager . ${npm_package_productName} --overwrite --platform=linux --arch=x64 --icon=assets/icons/png/icon.png --prune=true --ignore='(scaffold|src|builds|archive)' --asar.unpackDir=node_modules/ngrok/* --out=builds",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"build-bak": "run-os",
"build:win32": "electron-builder --win",
"build:darwin": "electron-builder --mac",
"clean": "rimraf ./dist",
"release": "electron-builder --publish always",
"postinstall": "electron-builder install-app-deps"
},
"build": {
"appId": "com.acme.app",
"productName": "ACME Electron",
"files": [
"**/*",
"builds/Release/*",
"assets/icons/*.*",
"assets/icons/mac/*.*",
"assets/icons/png/*.*",
"assets/icons/win/*.*"
],
"mac": {
"category": "public.build.automation",
"icon": "assets/icons/mac/icon.icns"
},
"dmg": {
"contents": [
{
"x": 110,
"y": 150
},
{
"x": 440,
"y": 150,
"type": "link",
"path": "/Applications"
}
],
"artifactName": "acme-app-${version}.${ext}"
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
},
{
"target": "portable"
}
],
"icon": "assets/icons/win/icon.ico"
},
"nsis": {
"runAfterFinish": true,
"installerIcon": "assets/icons/win/icon.ico",
"artifactName": "acme-app-${version}.${ext}"
},
"portable": {
"artifactName": "acme-app.exe"
},
"appx": {
"applicationId": "acme.app",
"backgroundColor": "#000000",
"identityName": "acme.app",
"publisherDisplayName": "nolandubeau",
"artifactName": "acme-app-${version}.${ext}"
},
"publish": [
{
"provider": "github",
"releaseType": "release"
}
]
},
"dependencies": {
...
},
"devDependencies": {
...
}
}
And here is my webpack.build.config.js:
const webpack = require('webpack');
const path = require('path');
//const BabiliPlugin = require('babili-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');
// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = [ SRC_DIR ];
module.exports = {
entry: SRC_DIR + '/index.js',
output: {
path: OUTPUT_DIR,
publicPath: './',
filename: 'bundle.js'
},
module: {
rules: [
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.json$/, loader: "json-loader" },
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
}),
include: defaultInclude
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/react'],
plugins: ['#babel/proposal-class-properties', '#babel/plugin-proposal-object-rest-spread', '#babel/plugin-syntax-dynamic-import']
}
}
},
{
test: /\.(jpe?g|png|gif)$/,
use: [
{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }
],
include: defaultInclude
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/, use: [
{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }
],
include: defaultInclude
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin({title: 'CaptureCloud Remote'}),
new ExtractTextPlugin("bundle.css"),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.LoaderOptionsPlugin({
debug: false,
optimization: {
minimizer: [
new UglifyJsPlugin({
sourceMap: true,
}),
],
}
})
//new BabiliPlugin()
],
stats: {
colors: true,
children: false,
chunks: false,
modules: false
}
};

How to set environmental variable in another env file in development and production environment?

I want to use another .env file in development and production.
For production build, I use npm run build:production and for development, I use npm run start.
But I didn't use environment variable.
In my project, env file is not used now. so when I build project, I should change some code.
I want to use env file.
ex:
development environment
npm run dev
production environment
npm run prod
development:
.env.dev
BASE_URL=http://localhost:3000
production:
.dnv.prod
BASE_URL=https://aaa.com
package.json
"scripts": {
"start": "webpack-dev-server",
"build": "webpack --progress --config webpack.config.ts",
"build:production": "webpack -p --progress --config webpack.config.ts",
"test": "echo \"Error: no test specified\" && exit 1"
}
webpack.config.ts
const config = {
entry: [
'react-hot-loader/patch',
'./src/index.tsx',
'./assets/styles/main.scss'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
devtool: 'source-map',
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.css', '.scss', '.json']
},
plugins: [
new Dotenv(),
new HtmlWebpackPlugin({
title: 'Hubbers v2',
chunksSortMode: 'dependency',
template: path.resolve(__dirname, './src/index.html')
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExtractTextWebpackPlugin('main.css'),
new CopyWebpackPlugin([
{from: 'assets/images', to: 'images'},
{from: 'assets/icons', to: 'icons'},
{from: 'src/_redirects', to: ''}
]),
new webpack.ContextReplacementPlugin(
/moment[/\\]locale$/,
/eu|cn/
)
],
module: {
loaders: [
{
test: /\.(png|jp(e*)g|webp|gif)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.woff(2)?(\?[a-z0-9]+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.(ttf|eot|otf|svg)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
},
{
test: /\.(css|scss)/,
use: ['css-hot-loader', ...ExtractTextWebpackPlugin.extract({
use: [
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: {
includePaths: [...require('bourbon').includePaths, ...require('bourbon-neat').includePaths]
}
}
]
})]
},
{
test: /\.json$/, loader: 'json-loader'
},
{
test: /\.tsx?$/,
loaders: [
'react-hot-loader/webpack',
'awesome-typescript-loader'
],
exclude: path.resolve(__dirname, 'node_modules'),
include: path.resolve(__dirname, 'src')
},
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader'
}
]
},
devServer: {
hot: true,
inline: true,
historyApiFallback: true
}
}
export default config
I see that you use dotenv-webpack. It supports specifying the path parameter. You can set the path parameter by env variable (sound ironic- to load ENV variables, you need an ENV variable...).
So you need to add path parameter to Dotenv constructor and set file depending on process.env.NODE_ENV variable:
{
plugins: [
new new Dotenv({
path: process.env.NODE_ENV === 'production' ? '.dnv.prod' : '.env.dev'
})
]
}
Then you need update your scripts to add NODE_ENV variable to webpack (documentation):
{
"scripts": {
"build": "webpack --env NODE_ENV=development --progress --config webpack.config.ts",
"build:production": "webpack --env NODE_ENV=production -p --progress --config webpack.config.ts",
}
}

Unable to copy bundle.js of a React project to Spring Project using webpack

I have a React project within a Spring project. I want to have a debug environment, where React files are watched, and are compiled & copied to the Spring project (different directory). I am using Webpack 4.8.
Currently I have to run npm run build:dev every time I make changes to the React code, correct bundle.js is created and is moved to the correct location. But running it every time is a hassle.
I've tried appending the script with --watch, and although it does create a new build, it isn't copied to the final location.
My package.json script
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node_modules\\.bin\\webpack-dev-server --config .\\webpack.dev.js",
"dev": "webpack --config .\\webpack.dev.js",
"build": "webpack --config .\\webpack.prod.js",
"copy:prod": "copy .\\dist\\bundle.js ..\\xxx\\src\\main\\resources\\static\\ /Y",
"copy:dev": "copy .\\dist\\bundle.js ..\\xxx\\build\\resources\\main\\static\\ /Y",
"build:dev": "npm run dev && npm run copy:dev",
"build:prod": "npm run build && npm run copy"
},
For anyone interested, this is my webpack.dev.js
const path = require("path");
const { resolve } = require("path")
const config = {
mode: "development",
entry: "./src/index.js",
stats: {
colors: true
},
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
}
]
}
};
module.exports = config;
Ideally, I'd like any changes to the React code to trigger a build, and copy the build to a different location. The current situation is that I am able to get the correct build using --watch but it's not being copied to the specified location.
Okay, so I used a library called copy-webpack-plugin.
And the updated webpack.dev.js file now looks like
const path = require("path");
const { resolve } = require("path");
const CopyPlugin = require('copy-webpack-plugin');
const config = {
mode: "development",
entry: "./src/index.js",
stats: {
colors: true
},
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
}
]
},
plugins: [
new CopyPlugin([
{ from: './dist/bundle.js', to: '../../xxx/build/resources/main/static/', force: true},
{ from: './dist/bundle.js.map', to: '../../xxx/build/resources/main/static/', force: true}
], { copyUnmodified: true })
]
};
module.exports = config;
And updated my npm script
"dev": "webpack --config .\\webpack.dev.js --watch",
Now when I run npm run dev I have the updated bundle.js copied in the desired location, and webpack also watches my React files.

Invalid configuration error while creating a react app with webpack configuration

Unable to configure webpack with react
below is error :
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.entry['main'] should not contain the item '—' twice.
-> A non-empty array of non-empty strings
I have configured webpack and tried
below is webpack.config.js
const path = require('path');
const HWP = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, '/src/index.js'),
output: {
filename: 'build.js',
path: path.join(__dirname, '/dist')},
module:{
rules:[{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
plugins:[
new HWP(
{template: path.join(__dirname,'/src/index.html')}
)
]
}
I solve this adding "--live-reload false" to my start command.
"scripts": {
"ng": "ng",
"start": "ng serve --live-reload false",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"build:single-spa:mf-test2": "ng build mf-test2 --prod",
"serve:single-spa:mf-test2": "ng s --project mf-test2 --disable-host-check --port NaN --live-reload false" },
i think this will work
const path = require('path');
const HWP = require('html-webpack-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'build.js',
path: path.join(__dirname, 'dist')},
module:{
rules:[{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}]
},
plugins:[
new HWP(
{template: path.join(__dirname,'src/index.html')}
)
]
}
changing scripts start command in package.json as below made it working,
"start": "webpack-dev-server --config webpack.config.js --port 3000",

Resources