How to use Phaser in Electron and React in 2024

I´m trying to set up a project with Phaser, React and Electron, using the electron-vite scaffolder, but I´m not having any luck with exposing Phaser to the renderer from the preload file.

After a lot of googling it seems like most solutions include turning on nodeIntegration and make an unsecure app, which doesn´t seem like a good idea.

Anyone have any tips on how to get it to work safely?

I don´t know what I did right or wrong, but after starting from scratch for the fifth time or so i got it to work, and got the react example up and running (Official Phaser 3 and React Template - Phaser).

But I can´t seem to load assets.

According to electron-vites documentation, the correct way to use images is to import them, and use the import as url, like this:

import imgUrl from '/assets/someImg.png'

<img src={imgUrl} />

I have confirmed that I can import and use the images with images tags this way, but I´m getting this error from the Phaser loader:

Refused to load the image 'blob:http://localhost:5173/84d4fa19-d924-4c95-83e1-57bd45eea2e3' because it violates the following Content Security Policy directive: "img-src 'self' data:".

Failed to process file: image "background" phaser.js?v=fd852cf7:65606

So any tips is still greatly appreciated!

I think I fixed it!

Step 1 was to add blob: to the Content-Security-policy in index.html as such:

<meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:"
    />

Step 2 was to remove this line from the (phaser) Preloader.ts script so the path doesn´t get mixed up:

this.load.setPath('assets');

And Voilà! Everything works as expected.

Any chance you can upload a template or example to github? This way people can have an easy starting point.

I don´t think that is a good idea. There are already a few phaser-electron templates out there, and they all seem to be outdated and insecure, and mine will probably end up that way eventually too, if it isn´t unsafe already.

It´s not a good idea to use an electron template from some random guy on the internet if you don´t know what you are doing, and if you do know what you are doing you don´t need the template.

You don´t know what malicious code I might have put in there, or which misstakes I made setting it up…

Either way, I´m about ready to leave the idea of electron behind (and probably Phaser alltogether) and go with a game engine made for desktop games. There are just so many problems, limitations, and hoops to jump through when developing electron apps.