webpack-dev-server#1.16.5 hot reload NOT working properly? - webpack-dev-server

starting webpack-dev-server --hot
i see the code run to client/index.js:
log("info", "[WDS] App hot update...");
console.log('window object',currentHash); //printed
window.postMessage("webpackHotUpdate" + currentHash, "*");
but not triggering below dev-server code:
hotEmitter.on("webpackHotUpdate", function(currentHash) {
console.log('inside weboackHotUpdate'); //not printed
lastHash = currentHash;
console.log('module.hot.status|'+ module.hot.status());
if(!upToDate() && module.hot.status() === "idle") {
log("info", "[HMR] Checking for updates on the server...");
check();
}
});
this affect the automatic refresh of window after hotmodulereplacement,
can anyone help?

i temporarily solved the window reload issue by add location.reload() after the window.postMessage, not sure how the post message "webpackHotUpdate" get handled if not from -hotEmitter.on("webpackHotUpdate",...- method

Related

Electron React app white screen + disconnected devtools in build but fine in development?

When I run my app on the development server (npm start) it works fine without any issues in the console.
However, when I build my app (npm run build && electron-builder -m) I get a white screen and disconnected devTools.
Here is my main.js file
const { app, BrowserWindow, screen } = require('electron')
let mainWindow;
function createWindow () {
// Create the browser window.
const { width, height } = screen.getPrimaryDisplay().workAreaSize
const win = new BrowserWindow({
title:"DSL viewer",
width:1050,
height:700,
maxHeight:height,
maxWidth:width,
minHeight:700,
minWidth:1050,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
devTools: true
}
})
win.loadURL('./index.html');
win.on('closed', function () {
mainWindow = null;
});
}
// 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', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Here is a screenshot of what the app looks like
Does anyone know what may be causing this or how I can go about debugging it?
Thanks in advance!
It is because electron is unable to find the index.html after build. Change window.loadURL to window.loadURL(__dirname+"/index.html").

Nextjs deployed on Vercel = blank page

I managed to deploy my Nextjs app (whith getStaticProps + i18n + firebase) on Vercel.
But i get a blank screen.
Here's the log:
Status: 200
Duration: 8.18ms
Memory Used: 111 MB
I tried :
Checking the build function locally: it works perfectly.
Changing the default build and development settings to these (with no luck) :
I even tried to deploy on netlify (even thought i don't think they support i18n because i18n doesn't support next export), but i get a 404 page, which is the equivalent of a blank page in Vercel.
I also tried:
Creating a new git and re-deploying. But I still get an empty result after a perfect deploy with a list of all my pages and stuff...
Deleting i18n.
Deleting index.html from public
Deleting all pages but one.
Deleting _document.jsx
Deleting every public folder pages except assets like images.
Deleting package lock file.
Stil nothing works.
And yet, i get a perfect previw of my webapp in Vercel, but the link goes to a blank page.
Any idea?
My mistake.
It was a problem with my getServerSideProps code
To this :
export async function getServerSideProps({ req, res }) {
const data = cookie.parse(req ? req.headers.cookie || "" : document.cookie);
if (res) {
if (Object.keys(data).length === 0 && data.constructor === Object) {
res.end();
}
}
return {
props: { userId: data.userId }, // will be passed to the page component as props
};
}
I went to this:
export async function getServerSideProps({ req, res }) {
const data = cookie.parse(req ? req.headers.cookie || "" : document.cookie);
return {
props: { userId: data.userId }, // will be passed to the page component as props
};
}
The res.end(); was the problem.
Deleting the following worked for me:
"homepage": "https://your-username.github.io/the-repo-project/",
vercel --prod
You have to wait a minute
But I think it depends on the project.
I ran into the same issue of having a blank page. I later discovered that I was running "npm run dev" in the wrong directory.
Instead of cd C:\wamp\www\projectname, I typed cd c:\wamp\www\projectname.
The difference is capital letter "C". Small letter "c" won't work.
Ensure your casing (capital or small) is right and everything spelt correctly. Then, run "npm run dev" and see your expected page display (if there are no other errors hindering it from showing).

importScripts in Web Workers is undefined inside a React/Webpack environment

I am working on a React app created with create-react-app. I was having trouble creating a web worker in it so I posted a question here on SO: Creating a web worker inside React
I've found a solution, as written in the post above, to load a worker without ejecting the app and messing with the Webpack config. This is the code, from the post above:
// worker.js
const workercode = () => {
self.onmessage = function(e) {
console.log('Message received from main script');
const workerResult = 'Received from main: ' + (e.data);
console.log('Posting message back to main script');
self.postMessage(workerResult);
}
};
let code = workercode.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
const blob = new Blob([code], {type: "application/javascript"});
const worker_script = URL.createObjectURL(blob);
module.exports = worker_script;
and in the file that uses the worker:
import worker_script from './worker';
const myWorker = new Worker(worker_script);
myWorker.onmessage = (m) => {
console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');
It works, however, I cannot seem to get importScripts to work. Even if I do this (outside onmessage or inside onmessage):
if (typeof importScripts === 'function') {
importScripts('myscript.js');
}
In that case, the if statement turns out to be true, but then fails on the actual import with the same error message 'importScripts' is not defined as if the if statement is a false positive, which doesn't sound right. I'd say this is a context issue and that the worker probably isn't loading properly (although it seems to work), but it's just a guess.
Any ideas what's happening here?
importScripts in a worker created from Blob works fine, at least in 2021 (react 17.0.2, react-scripts 4.0.3, Chrome 92). The imported script URL must be absolute because worker was created from Blob.
The original issue might have been a bug in webpack or the transpilation might have changed the code in a weird way.
const workercode = () => {
importScripts("https://example.com/extra.js");
console.log(self.extraValue); // 10
self.onmessage = function(e) {
console.log('Message received from main script');
...
}
};
 
// extra.js
self.extraValue = 10;
Looks like this is still broken in 2022 - Seems there is a regression coming down the dev pipeline (at least in Android WebView and possibly some dev/canary chrome verions.)
https://bugs.chromium.org/p/chromium/issues/detail?id=1078821

How to make Electron wait for npm start to finish

I have the following situation: I have a Angular CLI app, which is started by npm start. This operation may take some time to finish. After the start, the app is available at localhost:3000.
We then have an Electron app (made with nativefier module) which makes an app out of the url localhost:3000.
The problem arises when I start the Angular app and, in parallel, the Electron app, with a batch file. Obviously the Electron app will show an error as NPM start is not finished yet. On the other hand, I can't execute NPM start and the app sequentially, as the end user should not see the CMD window of NPM start (which I hide with a VBS script).
Ideally, the best solution would be that the Electron app and npm start fire on parallel and the Electron app would show a loading screen while NPM start is performing.
I have literally no idea how to achieve this.
Could someone address me to a solution?
Thanks
Fabio
The solution I found consists in having two different windows and playing with them, hiding the first one and show the second one when the latter is ready... So, imagine you want to show Google.com while waiting that localhost is ready
const {app, BrowserWindow} = require('electron')
let win
let win2
function createWindow () {
let win = new BrowserWindow({backgroundColor: '#2e2c29'})
win = new BrowserWindow({width: 800, height: 600, show:false})
win2 = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://localhost:3000')
win2.loadURL('http://www.google.com')
win.once('ready-to-show', () => {
win.show()
win2.hide()
win2.close()
})
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})

How to make the dev tools not show up on screen by default in Electron?

I am using electron-react-boilerplate to create an Electron-React app. The dev tools show up on the screen by default. How can I make the dev tools only appear when I ask for them and not show up on launch?
Also, there are no errors shown in the console, so the dev tools are not showing up because there's an error.
Just comment or remove this line of code in main.js file (setting devTools to false) this.mainWindow.openDevTools();
(or)
Add the following code to
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
webPreferences: {
devTools: false
}
});
(or)
change the package.json build to npm run build && build --win --x64
(or)
again install npm
If we add devTools: false in webPreferences, DevTools will not show when you start the Electron app. However, it can still be opened by pressing Ctrl + Shift + I.
webPreferences: {
devTools: false
}
Have a look at Slack. It is made with Electron and DevTools does not open when you press Ctrl + Shift + I.
I've had a look at Electron's official documentation, and I found a solution which doesn't allow DevTool's to open when you press Ctrl + Shift + I.
const { app, globalShortcut } = require('electron');
app.on('ready', () => {
// Register a shortcut listener for Ctrl + Shift + I
globalShortcut.register('Control+Shift+I', () => {
// When the user presses Ctrl + Shift + I, this function will get called
// You can modify this function to do other things, but if you just want
// to disable the shortcut, you can just return false
return false;
});
});
But, this will block all other browser's Ctrl + Shift +I
So, you can write the above code whenever your electron app is focused. And, remove it when your app is blur. This way you get a proper solution for this issue.
What makes the Developer Tools appear when the app starts is the line require('electron-debug')() in src/main/main.ts. This function has a showDevTools option which defaults to true, so you should change it to false:
require('electron-debug')({ showDevTools: false });
You will still be able to show the Developer Tools with the shortcut Ctrl + Shift + I or pressing F12, if you want to disable it completely, set webPreferences.devTools to false on new BrowserWindow:
mainWindow = new BrowserWindow({
// ... other settings
webPreferences: {
// ...
devTools: false,
},
});
Just add there these two bold line of code. You will not see devTool after packaging.
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
var debug = false
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
if(debug) mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// 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.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Every answer mentions that the keyboard shortcut CTRL + SHIFT + I still works even after disabling devtools using devTools: false.
This is because of the registered accelerator in the Electron BrowserWindow's default menu. All you have to do is remove the menu using mainWindow.removeMenu() and none of the development related shortcut keys will work again. Even the ones like CTRL + R which reloads the page.
Just want to add that, if you want to disable devTools only when in production mode, you can do:
new BrowserWindow({
webPreferences: {
devTools: !app.isPackaged,
},
})
P.S. This also prevents using shortcuts like Ctrl+Shift+I to toggle the devTools.
Just remove the line
mainWindow.webContents.openDevTools(false);
YEAR 2022
Code that loaded the devtools is in src/main/main.ts
Search this following code:
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
if (isDebug) {
require('electron-debug')();
}
you need to disable electron debug by comment it
//require('electron-debug')();

Resources