How to dynamically set port in electron and vite

272 Views Asked by At

I am trying to make a vite and electron app without the electron-vite boilerplate and i want a way to set the port (aka localhost:3000 ) dynamicaly, in case the default port is already being used.

I know how to manualy set the port with both vite and electron, and also know that vite have its own way to try another port if one is already in use (and certaily electron does to), but i have no idea on how i can make both decide on the same port.

My first attempt was to use the get-port package to find a usable port and then electron's inter-process communication (IPC) to send it to vite. but there is a catch:

  • My vite process should execute first or else the electron connection to port 3000 will be refused.
  • The IPC relies on configuring a preload.js (witch cant be used since vite has already loaded)*¹.

The simple and ugly "hack" i found was to make vite write the chosen port in a .txt or .json file and make electron read it before lauching the page. I dont like this solution, it looks messy and stinks. This looks like a simple problem for people who deal with electron and i am sure there is a best and known way to deal with it.

here is the repos: https://github.com/jvcmtr/TravelerGameProject

\The more I think about it, the more I think the project structure is not right. Am i really supose to launch the processess separetely on two diferent terminals, wasnt electron suposed launch the render process on its own? \

0

There are 0 best solutions below