react js- how to create exe file for react-electron

Viewed 173

i have a react app inside of my electron js i use electron-packager . for creating exe file of my project the exe file is generated success fully but the issue is that when i open the exe file only the electron app gets started since i dont do npm start my react app is not starting and the screen is white when the app start

in devlopement i can do npm start(to start react ) and then i can do npm run dev (to start electron) i am adding scripts that are in my pakage.json what changes must i do to fix this issue

"scripts": {
    "start": "electron .",
    "build": "react-scripts build",
    "dev": "electron .",
    "test": "react-scripts test",
    "electron": "npm:start && electron .",
    "eject": "react-scripts eject"
  },

enter image description here

const { app, BrowserWindow } = require("electron");
const isDev = require("electron-is-dev");

const path = require("path");
const url = require("url");
let mainWindow;

app.on("ready", () => {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 680,
    webPreferences: {
      nodeIntegration: true,
    },
  });

  // ...

  const urlLocation = isDev
    ? "http://localhost:3000"
    : url.format({
        // Running locally
        pathname: path.join(__dirname, "build/index.html"), // Adjust path here
        protocol: "file:",
        slashes: true,
      });
  // const urlLocation = isDev ? "http://localhost:3000" : "http://localhost:3000";
  mainWindow.loadURL(urlLocation);
  mainWindow.maximize();
});

when i do npm start this is how my electron app starts enter image description here

how do i connect my index.html file in build folder to electrons main.js file

folder structure of my react-electron project

folder structure of my react-electron project

enter image description here

enter image description here

enter image description here

1 Answers

Currently, in your main.js you loading HTTP URL from your react dev server, started separately with npm start.

Instead of this, you need to build react app, and point electron to dist index.html, without using web server.

Add this to your main.js:

const path = require('path')
const url = require('url')

// ...

const urlLocation = isDev
    ? "http://localhost:3000" // Running from dev server
    : url.format({ // Running locally
        pathname: path.join(__dirname, 'dist/index.html'), // Adjust path here
        protocol: 'file:',
        slashes: true
    });

Also consider using electron-react-boilerplate

Related