简体   繁体   中英

I create a build of my react app and connected with electron.js. now how to connect my backend from server folder with electron

I create a build of my react app and connected with electron.js. now how to connect my backend from server folder with electron.

How can I add backend to electron .exe

const { app, BrowserWindow } = require('electron')
const path = require('path')
require('./app');
                
function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
                
    // win.loadFile('./demo.html')
    win.loadFile('./build/index.html')
}
                
app.whenReady().then(() => {
    createWindow()
    
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})
                
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

This is my folder structure

在此处输入图像描述

Check your routing first in the frontend file (like an index.js in react) if it is BrowserRouter then change it to HashRouter. Now copy the below code and paste it to the electron main file

const { app, BrowserWindow } = require('electron')
const path = require('path')
const server = require('./app');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // win.loadFile('./demo.html')
  win.loadURL('http://localhost:9000')
  win.loadURL('./build/index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


// ******************************************************************************


/* const electron = require('electron')
const app = electron.app
handleSquirrelEvent(app)
const BrowserWindow = electron.BrowserWindow;
const path = require('path')
// const url = require('electron-is-dev');
const isDev = require('electron-is-dev');
let mainWindow;
// const createWindow = () => {
//     mainWindow = new BrowserWindow({ width: 800, height: 600 })
//     const appUrl = isDev ? 'http://localhost:3000' :
//         `file://${path.join(__dirname, '../build/index.html')}`
//     mainWindow.loadURL(appUrl)
//     // mainWindow.loadURL(url.format({
//     //     pathname: path.join(__dirname, '../build/index.html'),
//     //     protocol: 'file',
//     //     slashes: true
//     // }))
//     mainWindow.webContents.openDevTools()
//     mainWindow.on('closed', function () {
//         mainWindow = null
//     })
// }
// app.on('ready', createWindow)
// app.on('window-all-closed', function () {
//     if (process.platform !== 'darwin') {
//         app.quit()
//     }
// })
// app.on('activate', function () {
//     if (mainWindow === null) {
//         createWindow()
//     }
// })
const createWindow = () => {
  mainWindow = new BrowserWindow({ width: 480, height: 320 })
  const appUrl = isDev ? 'http://localhost:3000' :
    `file://${path.join(__dirname, '../build/index.html')}`
  mainWindow.loadURL(appUrl)
  mainWindow.maximize()
  mainWindow.setFullScreen(true)
  mainWindow.on('closed', () => mainWindow = null)
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
  // Follow OS convention on whether to quit app when
  // all windows are closed.
  if (process.platform !== 'darwin') { app.quit() }
})
app.on('activate', () => {
  // If the app is still open, but no windows are open,
  // create one when the app comes into focus.
  if (mainWindow === null) { createWindow() }
})
function handleSquirrelEvent(application) {
  if (process.argv.length === 1) {
    return false;
  }
  const ChildProcess = require('child_process');
  const path = require('path');
  const appFolder = path.resolve(process.execPath, '..');
  const rootAtomFolder = path.resolve(appFolder, '..');
  const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
  const exeName = path.basename(process.execPath);
  const spawn = function (command, args) {
    let spawnedProcess, error;
    try {
      spawnedProcess = ChildProcess.spawn(command, args, {
        detached: true
      });
    } catch (error) { }
    return spawnedProcess;
  };
  const spawnUpdate = function (args) {
    return spawn(updateDotExe, args);
  };
  const squirrelEvent = process.argv[1];
  switch (squirrelEvent) {
    // case '--squirrel-install': 58
    case '--squirrel-updated':
      // Optionally do things such as:
      // - Add your .exe to the PATH
      // - Write to the registry for things like file associations and
      //   explorer context menus
      // Install desktop and start menu shortcuts
      spawnUpdate(['--createShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-uninstall':
      // Undo anything you did in the --squirrel-install and
      // --squirrel-updated handlers
      // Remove desktop and start menu shortcuts
      spawnUpdate(['--removeShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-obsolete':
      // This is called on the outgoing version of your app before
      // we update to the new version - it's the opposite of
      // --squirrel-updated
      application.quit();
      return true;
    default:
      console.log("default case")
  }
};

 */

// ******************************************************************************

/* const electron = require('electron')
const path = require("path");
const url = require('url');
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow


process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
// 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.
  // 'public' is the path where webpack bundles my app
  mainWindow.loadURL(`file://${__dirname}/public/index.html`);

  // Open the DevTools.
  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()
  }
}) */`enter code here`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM