cant load react in electronjs - javascript

Here is my package.js file
{
"name": "cabed",
"version": "0.1.0",
"private": false,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"electron-forge": "^5.2.4",
"electron-is-dev": "^2.0.0",
"electron-packager": "^17.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"main": "public/electron.js",
"homepage": "./",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dev": "concurrently -k \"cross-env BROWSER=none npm start\" \"npm:electron\"",
"electron": "wait-on tcp:3000 && electron .",
"eb": "electron-packager C:/Users/user/cabed cddf --platform=win32 --arch=x64"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"concurrently": "^7.6.0",
"cross-env": "^7.0.3",
"electron": "^22.1.0",
"wait-on": "^7.0.1"
},
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "stock_trading_app"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin",
"linux",
"win32"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
]
}
}
}
The generated exe with electron builder which i ran with
npm run eb
the exe generated by code above
does not render the react app inside the opened windows app.
Here is my app js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div style={{justifyContent:'center',alignContent:'center',alignItems:'center'}}>
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<p>
Sasdsad
</p>
<p>
Sasdsad
</p>
</div></div>
);
}
export default App;
my electron.js looks like this under public directory.
const path = require('path');
const { app, BrowserWindow } = require('electron');
const isDev = require('electron-is-dev');
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, "./index.html")}`
);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: 'detach' });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
When running npm start first, then the exe renders react page inside window.
I need some configuration probably but i could not found it yet.

Since you said it works when you start your server first, I assume you're using the localhost URL both in dev and in prod. When your app is packaged, you should load the file in your window and not the local URL:
const { app } = require("electron");
const windowURL = app.isPackaged
? `file://${path.join(__dirname, "./index.html")}`
: "http://localhost:3000/";
mainWindow.loadURL(windowURL);
The path when your app is packaged might be different depending on your file structure and your build/package configurations. Also, don't forget to add "homepage": "./" on your package.json or you may get a blank page.

Related

Storybook with TailwindCSS in React (CRACO) and PostCSS does nothing

I've been trying to get Storybook to work with TailwindCSS in a CRA. However, I am unable to use any TailwindCSS classes and am getting this message when I start Storybook:
44% building 284/307 modules 23 active ...Documents\GitHub\<my project name>\node_modules\core-js\internals\set-to-string-tag.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
44% building 287/307 modules 20 active ...Documents\GitHub\<my project name>\node_modules\core-js\internals\set-to-string-tag.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
51% building 347/375 modules 28 active ...cuments\GitHub\<my project name>\node_modules\core-js\modules\es.symbol.unscopables.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
69% building 1065/1075 modules 10 active ...uments\GitHub\<my project name>\node_modules\core-js\modules\es.number.is-integer.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js
I've followed this guide. I've also checked the question here, and here's package.json:
{
"name": "some-project-name",
"version": "0.1.0",
"private": true,
"engine": {
"node": "^16.5.0"
},
"dependencies": {
"#craco/craco": "6.2.0",
"#testing-library/jest-dom": "5.11.4",
"#testing-library/react": "11.1.0",
"#testing-library/user-event": "12.1.10",
"express": "4.17.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-router-dom": "5.2.0",
"react-scripts": "4.0.3",
"styled-components": "5.3.0",
"web-vitals": "1.0.1"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject",
"prod:test": "yarn build && node server.js",
"prod:start": "yarn build && pm2-runtime server.js",
"dev:up": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
"dev:force": "docker-compose down && docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
"prod:up": "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up",
"prod:force": "docker-compose down && docker-compose -f docker-compose.yml -f docker-compose.prod.yml up",
"docker:build": "docker build .",
"storybook": "start-storybook -p 6006 -s public",
"build-storybook": "build-storybook -s public"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
],
"overrides": [
{
"files": [
"**/*.stories.*"
],
"rules": {
"import/no-anonymous-default-export": "off"
}
}
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#storybook/addon-actions": "6.3.5",
"#storybook/addon-essentials": "6.3.5",
"#storybook/addon-links": "6.3.5",
"#storybook/node-logger": "6.3.5",
"#storybook/preset-create-react-app": "3.2.0",
"#storybook/react": "6.3.5",
"autoprefixer": "9",
"postcss": "7",
"tailwindcss": "npm:#tailwindcss/postcss7-compat"
},
"resolutions": {
"babel-loader": "8.1.0"
}
}
Here's the craco.config.js:
module.exports = {
style: {
postcss: {
plugins: [require('tailwindcss'), require('autoprefixer')],
},
},
};
.storybook/main.js:
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
addons: ['#storybook/addon-links', '#storybook/addon-essentials', '#storybook/preset-create-react-app'],
webpackFinal: async (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: 'postcss-loader',
options: {
// HERE: OPTIONS
postcssOptions: {
plugins: [require('tailwindcss'), require('autoprefixer')],
},
},
},
],
include: path.resolve(__dirname, '../'),
});
return config;
},
};
postcss.config.js (which I don't think matters here but just in case):
const tailwindcss = require('tailwindcss');
module.exports = {
plugins: [
tailwindcss('./tailwind.config.js'),
require('autoprefixer'),
],
};
tailwind.config.js:
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
fontFamily: {
sans: ['Montserrat'],
},
extend: {
screens: {
mx: '2048px',
},
},
variants: {
extend: {},
},
plugins: [],
},
};
I'm not able to use TailwindCSS styles in my stories components.
Here's the demo Button component:
import React from 'react';
import PropTypes from 'prop-types';
import './button.css';
/**
* Primary UI component for user interaction
*/
export const Button = ({ primary, backgroundColor, size, label, ...props }) => {
return (
<button type="button" className="bg-gray-900" {...props}>
{label}
</button>
);
};
Button.propTypes = {
/**
* Is this the principal call to action on the page?
*/
primary: PropTypes.bool,
/**
* What background color to use
*/
backgroundColor: PropTypes.string,
/**
* How large should the button be?
*/
size: PropTypes.oneOf(['small', 'medium', 'large']),
/**
* Button contents
*/
label: PropTypes.string.isRequired,
/**
* Optional click handler
*/
onClick: PropTypes.func,
};
Button.defaultProps = {
backgroundColor: null,
primary: false,
size: 'medium',
onClick: undefined,
};
The Button:
HTML in DOM:
<button type="button" class="bg-gray-900">Button</button>
Not sure where to go from here...
Update:
Went to webpack and postcss docs, and removed the options from .storyboard/main.js so use just looks like this:
use: [
{
loader: 'postcss-loader',
},
],
Now it's actually grabbing the plugins from postcss.config.js:
module.exports = {
plugins: [require('autoprefixer'), require('tailwindcss')],
};
So the warning about no plugins found went away. But still no visible change on the website.

StompJs starting two websocket connections

React application, #stomp/stompjs library
If I start React app, it opens 2 websocket connections.
console log
network log
If I build and deploy it to server, it opens only one connection.
console log
network log
chat.js
import React from 'react';
import { Client, Message } from '#stomp/stompjs';
function Chat(props) {
const client = new Client({
brokerURL: 'ws://localhost:8088/api/chat',
debug: function (str) {
console.log(str);
},
reconnectDelay: 5000,
});
client.onConnect = function (frame) {
client.subscribe("/chat", function (message) {
console.log("MESSAGE: " + message)
})
};
client.onStompError = function (frame) {
console.log('Broker reported error: ' + frame.headers['message']);
console.log('Additional details: ' + frame.body);
};
client.activate();
return (
<p>chat</p>
);
}
export default Chat
package.json
{
"name": "react-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#stomp/stompjs": "^6.1.0",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"dotenv": "^10.0.0",
"http-proxy-middleware": "^2.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2",
"websocket": "^1.0.34"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && mv build/* ../src/main/resources/static'",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I don't want to always build my app or receive double events. How can I fix that?
WebSocket is a "side effect" and React.useEffect fixed it
https://stackoverflow.com/a/57809487

Getting blank screen in windows after electron-builder react electron app

Getting blank screen in windows after electron-builder react electron app.
Here is package.json. Getting blank screen in windows after electron-builder react electron app.
{
"name": "SmallBusinessManagement",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^4.5.3",
"cross-env": "^7.0.2",
"date-fns": "^2.16.1",
"electron-is-dev": "^1.2.0",
"jquery": "^3.5.1",
"jspdf": "^2.1.1",
"jspdf-autotable": "^3.5.13",
"knex": "^0.21.12",
"moment": "^2.29.1",
"popper.js": "^1.16.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-popper": "^2.2.4",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"sqlite3": "^5.0.0",
"wait-on": "^5.2.0",
"web-vitals": "^0.2.4"
},
"scripts": {
"postinstall": "electron-builder install-app-deps",
"dist": "electron-builder",
"pack": "electron-builder --dir",
"react-start": "react-scripts start",
"react-build": "react-scripts build",
"react-test": "react-scripts test",
"react-eject": "react-scripts eject",
"electron-build": "electron-builder",
"release": "yarn react-build && electron-builder --publish=always",
"start": "concurrently \"cross-env BROWSER=none yarn react-start\" \"wait-on http://localhost:3000 && electron .\""
},
"build": {
"productName":"SmallBussinessManagement",
"appId": "com.smallbusinessmanagement",
"dmg": {
"contents": [
{
"x": 110,
"y": 150
},
{
"x": 240,
"y": 150,
"type": "link",
"path": "/Applications"
}
]
},
"win": {
"target": "NSIS",
"icon": "build/icon.ico"
},
"directories": {
"buildResources": "resources",
"output": "release"
}
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"description": "Small business management is used to manage daily sell and buy.",
"author": "rakshithgowda KV",
"main": "public/electron.js",
"homepage": "./addItem",
"devDependencies": {
"electron": "latest",
"electron-builder": "latest"
},
"files": [
"*.js",
"build",
"node_modules"
]
}
public/electron.js. Do i need to isntall any dependency ?
const { app, BrowserWindow,Menu } = require('electron')
require('../src/messgaeController/main');
const path = require("path");
const isDev = require("electron-is-dev");
let addItem ;
let win;
function createWindow () {
win = new BrowserWindow({
width: 800,
height: 600,
icon:"build/icon.ico",
webPreferences: {
nodeIntegration: true,
// webSecurity: false
}
})
win.loadURL(isDev? "http://localhost:3000": `file://${__dirname}/../build/index.html`);
win.on("closed", () => (mainWindow = null));
const mainMenu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(mainMenu);
// win.webContents.openDevTools()
win.on("close",()=>app.quit())
}
Not sure why it's showing blank page after build. Tried different approach, didn't work
enter image description here
Not sure if you had implemented routing in ReactJS, but I fixed by using HashRouter instead of BrowserRouter...
example:
return (
<HashRouter>
<div>
<Header/>
<Switch>
<Route path="/" component={Home} exact/>
<Route path="/news" component={News} exact/>
<Route path="/store" component={Store} exact/>
<Route path="/login" component={Login} exact/>
<ProtectedRoute path="/profile" component={Profile} exact/>
</Switch>
</div>
</HashRouter>
)
Incase someone stumbles upon this like I did, I solved my issue by changing
win.loadURL(isDev? "http://localhost:3000": `file://${__dirname}/../build/index.html`);
to
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
ensure you require path and url and also let mainwindow
const path = require("path");
const url = require('url');
let mainWindow;
also I changed
win.on("closed", () => (mainWindow = null));
to
mainWindow.on("closed", () => (mainWindow = null));
I also change router history to hash
import { createHashHistory } from 'history';
export default createHashHistory();
This problem is due to the wrong link between the build folder & entry point of your app
DON’T USE in this way
mainWindow.loadURL(isDev ? ‘http://localhost:3000' : file://${path.join(__dirname, ‘../build/index.html’)});
USE IN THIS WAY
mainWindow.loadURL(isDev ? ‘http://localhost:3000' : file://${__dirname}/../build/index.html);
and if you use React router you must replace (Router) >> (HashRouter)
const { app, BrowserWindow } = require('electron')
const appURL = app.isPackaged
? url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true,
})
: "http://localhost:3000";
mainWindow.loadURL(appURL);
if (!app.isPackaged) {
mainWindow.webContents.openDevTools();
}

How to make react project exe with electron.js

I am trying to make the exe file of my reactjs project with the help of electron.js but i am nota able to create that, its just showing white screen after creation. Any idea, how to do that.
My package.json
{
"name": "demo",
"version": "0.1.0",
"private": true,
"description": "desc",
"author": "author",
"homepage": "./",
"main": "public/electron.js",
"scripts": {
"react-start": "react-scripts start",
"react-build": "react-scripts build",
"react-test": "react-scripts test --env=jsdom",
"react-eject": "react-scripts eject",
"electron-build": "electron-builder",
"preelectron-pack": "npm run-script build",
"release": "yarn react-build && electron-builder --publish=always",
"build": "yarn react-build && yarn electron-build",
"ebuild": "npm run build && node_modules/.bin/build",
"dev": "concurrently \"npm start\" \"wait-on http://localhost:3000 && electron .\"",
"start": "concurrently \"cross-env BROWSER=none yarn react-start\" \"wait-on http://localhost:3000 && electron .\"",
"compile": "yarn electron-compile"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"babel-preset-react": "^6.24.1",
"electron": "^11.3.0",
"electron-builder": "^22.9.1",
"electron-packager": "^15.2.0",
"electron-reload": "^1.5.0",
"nodemon": "^2.0.7",
"nw": "^0.44.1-sdk",
"nw-builder": "^3.5.7"
},
"build": {
"appId": "12340214",
"extends": null,
"win": {
"icon": "Assets/icons/win/icon.ico"
},
"files": [
"build/**/*",
"node_modules/**/*",
"dist/**/*",
"package.json",
"./public/electron.js"
],
"directories": {
"buildResources": "assets"
}
}
}
public/electron.js:
const { app, BrowserWindow } = require('electron');
// const isDev = require('electron-is-dev');
const path = require('path');
// const url = require('url');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width:800,
height:600,
show: false
});
// const startURL = isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`;
const startURL = `file://${path.join(__dirname, '../build/index.html')}`;
// mainWindow.loadURL(url.format({
// pathname: path.join(__dirname, 'index.html'),
// protocol: 'file:',
// slashes: true
// }));
mainWindow.loadURL(startURL);
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
Whenever i try to run the commands, the setup file is created but it is showing only white screen, and when i try to run it simple i.e normal electron cmd to run the react project in app window it runs successfully.

Trying to run my node.js server at same time as React .js App and get: 'ERR_MODULE_NOT_FOUND'

I've set up a server for an ecommerce site I am building in React and trying to run both the React app and the server at the same time but keep getting errors - and after solving them getting more. None of the fixes I have found online work.
I use npm run dev so to run the application in development server and run the node server at the same time (package.json is included and shows how I set it up) - however I get these warnings and errors:
I do not know why it cant finde the module it is talking about because the files are there and imported etc.. the relevant code is posted below.
package.json:
{
"name": "ecommerce",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.3",
"#testing-library/user-event": "^12.6.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"server": "node-env-run server --exec nodemon | pino-colada",
"dev": "run-p server start"
},
"type": "module",
"keywords":[
"ES",
"MODULES",
"NODE",
"MODULES",
"JS"
],
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/node": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"express-pino-logger": "^5.0.0",
"node-env-run": "^4.0.2",
"nodemon": "^2.0.7",
"npm-run-all": "^4.1.5",
"pino-colada": "^2.1.0"
},
"proxy": "http://localhost:3001"
}
server/index.js:
import data from './data';
const express = require('express');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);
app.get('/api/prodcuts', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(data.products);
});
app.listen(3001, () =>
console.log('Express server is running on localhost:3001')
);
server/data.js:
const data = {
products: [
{
_id: '1',
name: 'Charizard',
category: 'Pokemon Cards',
image: '/Images/d1.jpg',
price: 60,
rating: 4.5,
numReview: 10
},
{
_id: '2',
name: 'Squirtle',
category: 'Pokemon Cards',
image: '/Images/d2.jpg',
price: 30,
rating: 4.1,
numReview: 10
},
{
id: '3',
name: 'Mew',
category: 'Pokemon Cards',
image: '/Images/d3.jpg',
price: 500,
rating: 4.8,
numReview: 10
}
]
}
export default data;
If there is anything else I need to add please let me know!
I had the same problem It just required me to add file extension when importing
import data from './data.js'

Categories

Resources