After turning a react app into a PWD the url changes - reactjs

I have a react app that works on for example http://localhost:3000/ after I add the config to make it a PWA the url change to http://localhost:3000/my-app.
Is this normal behaviour or is my config?
This is my worker.js
// /my-app/public/worker.js
let CACHE_NAME = "my-app";
let urlsToCache = ["/", "/completed"];
let self = this;
// Install a service worker
self.addEventListener("install", (event) => {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
console.log("Opened cache");
return cache.addAll(urlsToCache);
})
);
});
// Cache and return requests
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then(function (response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
})
);
});
// Update a service worker
self.addEventListener("activate", (event) => {
let cacheWhitelist = ["my-app"];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
This is my manifest.json
// /my-app/public/manifest.json
{
"short_name": "My App",
"name": "My App",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
This is the pachage.json
// /my-app/package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"homepage": "http://<username>.github.io/my-app",
"dependencies": {
"gh-pages": "^3.1.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I have tried to change "my-app" in worker.js, and in package.json but that doesn't seem to change anything, maybe the config of that is in another place?
And now if I go to http://localhost:3000/ I get a blank page and the error
bundle.js:1 Uncaught SyntaxError: Unexpected token '<'
0.chunk.js:1 Uncaught SyntaxError: Unexpected token '<'
main.chunk.js:1 Uncaught SyntaxError: Unexpected token '<'
(index):39 Worker registration successful http://localhost:3000/
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
If this is not normal, how can I change it to just be http://localhost:3000/ again?

Related

Electron app not running after building with electron-forge [duplicate]

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.

How to fix “Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0” ERROR

After hours of searching the web I have not found the solution to my problem. So I am building a full-stack CRUD app on React & Java Spring Boot. So far I have been able to run the backend soring boot on localhost://8080. The problem appears when I run the frontend React on localhost://3000 -> The React App keeps loading & I see “Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0” the error in the console.
App.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
isLoading: true,
groups: []
};
async componentDidMount() {
const response = await fetch('/api/groups');
const body = await response.json();
this.setState({ groups: body, isLoading: false });
} ->
get syntax error here
render() {
const {groups, isLoading} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<div className="App-intro">
<h2>JUG List</h2>
{groups.map(group =>
<div key={group.id}>
{group.name}
</div>
)}
</div>
</header>
</div>
);
}
}
export default App;
package.json:
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"bootstrap": "4.1.3",
"react": "^16.14.0",
"react-cookie": "3.0.4",
"react-dom": "^16.14.0",
"react-router-dom": "4.3.1",
"react-scripts": "3.4.3",
"reactstrap": "6.5.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"proxy": "http://localhost:8080" //====>PROBLEMATIC CODE(should be outside
//the script block)
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
response.json:
{
"$id": "response.json#",
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"required": [
"status",
"statusText",
"httpVersion",
"cookies",
"headers",
"content",
"redirectURL",
"headersSize",
"bodySize"
],
"properties": {
"status": {
"type": "integer"
},
"statusText": {
"type": "string"
},
"httpVersion": {
"type": "string"
},
"cookies": {
"type": "array",
"items": {
"$ref": "cookie.json#"
}
},
"headers": {
"type": "array",
"items": {
"$ref": "header.json#"
}
},
"content": {
"$ref": "content.json#"
},
"redirectURL": {
"type": "string"
},
"headersSize": {
"type": "integer"
},
"bodySize": {
"type": "integer"
},
"comment": {
"type": "string"
}
}
}
SOLUTION:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080"
GitHub Repo
What is the response returned by the /api/groups call? Based on the error message, it is likely that the response is in HTML format. But it is being parsed as JSON (in the response.json()) call.
Try to temporarily change your code to the following:
const body = await response.text();
console.log(body);
Or use the network tab to inspect the server's response.
"proxy": "http://localhost:8080"
Above line should be outside the Scripts block below. Because "proxy" is not a part of scripts, but rather a port that talks to the react server see details Like SO:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080"

how to fix Jest encountered an unexpected token React

I m trying to run a react app, created using create-react-app. App runs successfully, but when I try to run JEST it give me the following error. I have looked and tried various options but could not fix it. Here is my package.json and jest.config.json
please suggest on what I might be doing wrong
Thank you
A
Error
FAIL src/App.test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
SyntaxError: C:\Test\counter-app\src\App.test.js: Unexpected token (7:18)
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
> 7 | ReactDOM.render(<App />, div);
| ^
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
package.json
{
"name": "counter-app",
"version": "0.1.0",
"private": true,
"jest": {
"verbose": true,
"moduleDirectories": ["node_modules", "src"],
"transformIgnorePatterns": [
"node_modules/(?!(react-native|react-native-cookies)/)"
]
},
"dependencies": {
"bootstrap": "^4.3.1",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --env=jsdom",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
jest.config.js
const {defaults} = require('jest-config');
module.exports = {
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.(css|scss|less)$": "jest-css-modules",
".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
},
"globals": {
"NODE_ENV": "test"
},
moduleFileExtensions: [...defaults.moduleFileExtensions, 'js', 'jsx'],
"moduleDirectories": [
"node_modules",
"src/frontend",
"src/shared"
]
};
Modified Package.json as follows:
{
"name": "foo",
"version": "0.1.0",
"private": true,
"dependencies": {
"jest-junit": "^9.0.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"reporters": [ "default", "jest-junit" ],
"test": "react-scripts test --watchAll=false",
"testResultsProcessor": "jest-junit",
"eject": "react-scripts eject"
},
"jest-junit": {
"suiteName": "jest tests",
"outputDirectory": ".",
"outputName": "junit.xml",
"uniqueOutputName": "false",
"classNameTemplate": "{classname}-{hello}",
"titleTemplate": "{classname}-{helloTests}",
"ancestorSeparator": " › ",
"usePathForSuiteName": "true"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Try removing jest.config.js file completely and let it work with default config.

Chrome-debugger requires authorization after launching

I used create-react-app to create new react application. I have not changed absolutely anything except for adding configuration "Chrome-launch" into launch.json. After debug launching it always requires some authorization. According to chrome.debugger documentation I added to manifest.json this:
"permissions": [ "debugger"]
But it did not help. Now I have no idea how to get through it. Please, could someone give me a hint how to launch chrome-debugger without any authorization?
I have used this debugger many times in the past and it never required authorization, I have no idea what has changed.
Behaviour in the browser:
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}
manifest.json:
{
"short_name": "React App",
"name": "Create React App Sample",
"permissions": [
"debugger"
],
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
package.json:
{
"name": "kinosal",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

How to set entry point/start page for electron app on win10 correctly in production build

I have created a react app and want to wrap it in electron to run it on win10, since the App needs node-seriaport.
Everything works fine in development mode, but I don´t get the app running properly in production mode, i.e. when packed.
The App starts on the wrong page and images and files in extra resources are not loaded properly since the routing/pathes are not correct.
The packing itself works fine, but when i run the .exe file the app starts on the 404-Route, which I have implemented as a catch all in react-router. When loggin in the chrome console, where the app actually wanted to go i see the following route:
pathname: "/C:/UserData/somefolder/otherfolder/dist/win-unpacked/resources/app.asar/build/index.html"
- which would be correct if there wasn´t that / at the start.
I have some files in the extraResource folder, but i am not able to access this folder in production/packed mode, in the sources tab in Chrome the extraResources Folder is not part of the main app directory but is shown seperatly, meaning it is expected to be under C:\, how can I configure this correctly?
As said in dev mode everthing works fine.
I think it all starts with the right route for the entry point, can´t someone provide me a hint what I need to do to get that working?
Here is my package.json
{
"name": "app-name",
"version": "0.1.0",
"private": true,
"main": "./public/electron.js",
"author": "CG",
"description": "description",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron": "set ELECTRON_START_URL=http://localhost:3000 && electron .",
"rebuild": "./node_modules/.bin/electron-rebuild -f -w serialport",
"electron-pack": "build --win --x64 --dir"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"electron": "^4.0.4",
"electron-packager": "^13.1.1",
"electron-rebuild": "^1.8.4"
},
"build": {
"appId": "com.wmt.wmt-1",
"files": [
"build/**/*",
"node_modules/**/*"
],
"directories":{
"buildResources": "public"
},
"extraResources": [
{
"from": "./public/extraResources/",
"to": "extraResources",
"filter": [
"**/*"
]
}
]
},
"win": {
"icon": "/public/img/icon.png"
},
"homepage": "./"
}
Here is the electron.jsfile:
const {app, BrowserWindow, protocol} = require('electron')
const path = require('path');
const url = require('url');
let mainWindow
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '/../build/index.html'),
protocol: 'file:',
slashes: true,
});
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
mainWindow.loadURL(startUrl);
// Open the DevTools.
mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', () => {
createWindow()
});

Resources