#Electron + React & Multiple Windows

68 messages · Page 1 of 1 (latest)

amber river
#

Is anyone familar with any projects that use react in multiple electron windows? Trying to find an example to learn from..

Ill try and explain for someone who may take the time to read

So right now Im running my main react app inside of the MainWindow after using react-scripts start and loading up
inside of my electron.js(main.js) I spawn the mainWindow.. Now inside of the main window I have an 'option' to spawn a new window... this new window should also have access to the react components but in its current state it does not..

both my 'index.html and my 'obs.html' are both located in the public folder.. index.html is in the root and obs.html is in a windows/obs/obs.html

When I try and access react components in the obs.html it complains about 'require is not defined'..
and so chatgpt says about balel and webpack but I cant find any info on this precisely so i think its making things up

I feel like since I already have index.html working with react why shouldnt this obs.html as well

halcyon galleon
#

alright, so first thing, what did you put inside osx.html to get the require error?

#

I will explain after why React doesn't work on the second HTML

amber river
#

its obsRenderer that has the error right now.. - i changed things up mildly..

const React = require('react');
const ReactDOM = require('react-dom/client'); // Ensure you're using createRoot with React 18
const ObsSourceMapping = require('./ObsSourceMapping');

window.addEventListener('DOMContentLoaded', () => {
  const rootElement = document.getElementById('OBS-root');
  const root = ReactDOM.createRoot(rootElement);
  root.render(<ObsSourceMapping />);
});
#

and this is obs.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OBS Source Mapping</title>
</head>
<body>
  <div id="OBS-root"></div>
  <script src="./obsRenderer.js"></script>
</body>
</html>
halcyon galleon
#

Okay so yes, you use require, which is forbidden by default for security reasons

amber river
#

when I use import, I end up with this
Uncaught SyntaxError: Cannot use import statement outside a module (at obsRenderer.js:5:1)

despite me usingthe same style importsin my main app.js

halcyon galleon
#

Yep

#

Do you know how CRA (react-scripts) works or not at all?

amber river
halcyon galleon
#

no problem

amber river
#

I might know, when you mention but to be safe... no 😛

halcyon galleon
#

basically, CRA is just a preconfigured tool that allow you to create a React app quicky. Inside react-script, there is webpack, which is the bundler it use to compile your files

#

A bundler will use various others tools that among other things allow you to use import, and compile your files into small neat files you can use for production (I'm simplifying everything so you get the idea)

amber river
#

I follow along on that first bit..

this obs.html/renderer/preload etc are al residing in my public folder, which I thought the 'CRA' would pick up automatically and package things as it does for app.js

which is why I was a bit confused as to why it didnt work 'out of the box' when i tried it..

halcyon galleon
#

It's because by default, CRA is only configured to server a single entry point

halcyon galleon
#

usually Single Page Applications only need one

#

Now in your case, you have multiple options

#

first, you may want to know that CRA is deprecated and no longer maintained

#

so my best recommendation would be to just remove it and replace it with Vite

#

but, if for some reasons you can't or don't want to do that for now, I can explain how you can add extra entry points

amber river
#

I have no problems switchingit up since its no longer maintained.. im just creating this app and dont want to deal with issues in future due to that

halcyon galleon
#

well yes, because you can configure the entry points as you want. You could also make your own webpack config if you rather use Webpack instead of Vite

#

or any other bundler

halcyon galleon
#

because otherwise you would need to either eject CRA or override its config and it's not ideal nor easy

#

If you're not comfortable about configuring Vite yourself for Electron you can also use pre-made tools like one of the two electron-vite for example

#

you would just need to add the React plugin on them

amber river
halcyon galleon
#

hmm, I don't think it's that complicated but I've never tried these tools, I've made my own instead x)

amber river
halcyon galleon
amber river
# halcyon galleon I just took `react-scripts` config, removed everything I didn't need and added s...

Certainly ran into a few issues along the way but did manage to get everything working in dev environment anyhow, minus my original issue/concern though but I am tackling that now that I am using vite


My current issue/concern would be the current project structure and if its ok for this given scenario?

I want to make sure I am putting things in the proper place when I 'copied' over...

Besides that though my error is a wee bit different this time around.
I still cant seem to get the react to render in the obs.html using obsrenderer.js I get a very basic error

obsRenderer.js:8 Uncaught SyntaxError: Unexpected token '<' 

halcyon galleon
#

This error is because Vite doesn't support .js extension when using JSX

amber river
#

root.render(<ObsSourceMapping />) is line 8

halcyon galleon
#

you need to use .jsx for React

amber river
#

ok swapped that out earlier with same error actually as well..

halcyon galleon
#

most probably because you can't load JSX like this in the Dom directly if it's not handled by Vite

#

how is it on the index.html? What's your Vite config?

#

and again, you should not use require on the renderer process

amber river
#
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>The One to Rule Them All</title>    
  </head>
  <body>
    <div id="root" ></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

and thats rendered by this main.jsx

import './assets/main.css'

import React from 'react'
import ReactDOM from 'react-dom/client'
import { CurrentGameConfigProvider } from './context/currentGameConfig';
import { MatchDataProvider } from './context/MatchDataContext';
import { AppProvider } from './context/AppContext';
import Frame from './components/UI/Frame'

import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
    <MatchDataProvider>
      <CurrentGameConfigProvider>
        <AppProvider>
        <Frame>
          <App />
        </Frame>
        </AppProvider>
      </CurrentGameConfigProvider>
    </MatchDataProvider>
)
halcyon galleon
#

I would suggest to write the script the same way
And your Vite config?

amber river
#

electron.vite.config.mjs

import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  main: {
    plugins: [externalizeDepsPlugin()]
  },
  preload: {
    plugins: [externalizeDepsPlugin()]
  },
  renderer: {
    resolve: {
      alias: {
        '@renderer': resolve('src/renderer/src')
      }
    },
    plugins: [react()],
    server: {
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
        '/update-json': {
          target: 'http://localhost:8080',
          changeOrigin: true,
        },
        '/config': {
          target: 'http://localhost:8080',
          changeOrigin: true,
        },
        '/getHeroFiles': {
          target: 'http://localhost:8080',
          changeOrigin: true,
        },
        '/files': {
          target: 'http://localhost:8080',
          changeOrigin: true,
        },
      },
    },
    
  }
})

Ok i went ahead and tried to render it the same way and the error below came up..
SyntaxError: Cannot use import statement outside a module
and then if i enalbe modules via package.json then other thingss brea as their 'requires' are now broken

So basically back where we started when I first made this thread I reckon but with vite now.

halcyon galleon
amber river
#

il check those links out ya got there

halcyon galleon
#

second link then

#

first*

amber river
# halcyon galleon second link then

oki thanks.. Ill try and dig more into it. cant seem to get it to act any different after following that format just yet..

and I have 'other' windows which open fine that dont needtis special treatment.. but they also dont use react in them besides mainWindow so thats likely why theres a difference

halcyon galleon
#

You need to understand that React needs a build tool to work

#

if you want to use React, you can't just magically throw it on a HTML and expect it to work

#

you need to register a new entry point on your bundler (Vite for you), to tell it to compile React to something native that the HTML can display

#

it's not even related to Electron

#

try to put your jsx file on a regular HTML you open on the browser and you will see what happen

#

the docs show you an example with two entry points

#

I'm not sure about the exact config you need for React though

amber river
#

yea I saw that xample and tried to follow it as well..
samething occurs unfortunately.

halcyon galleon
#

what error?

amber river
amber river
#

I am thinking perhaps I should ismply just render a component inside of the main window/app as a modal instead..

I do have multiple other windows that work fine but none of them are using react.. but they also dont 'need' it either

halcyon galleon
amber river
# halcyon galleon Have you updated the script tag?

ahh yea script type="module" is set now..

new error occured, tried to debug it but no go.. I tried to match everything exactly as the main window as far as creating it and injecting into the root element

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

tried some debugging via web which lead me to some config changes but It didnt even cause the error to chagne up..

amber river
#

--
i removed all the new electron.vite.config changes i did and the same error remains so thats even more interesting to someone like myself.. i expected something

halcyon galleon
#

what's your current vite config?