electron-vite/electron-vite-react

[Help] Cannot spawn new process

peterdee opened this issue · 2 comments

Hi.

I am developing an app and I am trying to spawn a new process in main with child_process.fork():

// main.ts
import { fork } from 'node:child_process';
import path from 'node:path';

app.whenReady().then(() => {
  ipcMain.handle('worker', async (event, args: string[]) => {
      const child = fork(path.join(__dirname, 'worker.js'));
    
      const spawnPromise = await new Promise<boolean>((resolve) => {
        child.on('spawn', () => {
          resolve(true);
        });
      });
  
      const messagePromise = await new Promise<string>((resolve) => {
        child.on('message', (data: string) => {
          resolve(data);
        });
      });
  
      child.send(args);
      return messagePromise;
  });

  createWindow();
});

// worker.ts
process.on('message', (strings = []) => {
  if (!process.send) {
    return process.exit(0);
  }
  return process.send(strings.join(''));
});

Unfortunately this code does not work, because worker.ts not getting copied as a separate file to the electron-dist/main directory.

If I import it in main.ts (just import './worker'; at the top of the file) it will be bundled into main.js, and the code above still won't work, since I need a separate worker file.

My question is: how should I copy worker file into electron-dist? Should I update vite.config.ts to just copy the file into electron-dist?

main.entry supports array. Add your worker file path there

This worked, thank you.