vite-plugin-electron icon indicating copy to clipboard operation
vite-plugin-electron copied to clipboard

Correct way of using workers in main

Open hyperknot opened this issue 1 year ago • 2 comments

First of all, thanks for creating the most polished Electron Vite framework. I looked at all of them and arrived at this!

My question is, what is the recommended, modern way to use a Node.js Worker in the main process? I've looked through the examples but couldn't seem to find one covering this specific scenario.

The most information I found was in this PR from ~3 years ago: https://github.com/electron-vite/vite-plugin-electron/pull/89

However, it's referring to a sample (examples/worker) which appears to have been removed since: https://github.com/electron-vite/vite-plugin-electron/tree/main/examples/worker

The code snippets in that PR show using an array format for the entry option in the electron plugin:

electron({
  entry: [
    'electron/main.ts',    // Example main entry
    'electron/worker.ts',  // Example worker entry
  ],
})

Does this multi-entry configuration approach still work today for bundling a main process worker?

And afterward, what should I do in main.ts to instantiate the worker? Is it something like:

new Worker(path.join(__dirname, './worker.js'))?

If so, what should the filename (worker.js in the example) actually be, considering it originates from a TypeScript file (like worker.ts) and gets built into the output directory?

Also, related to instantiation, what syntax should I use? Are any of these examples (from the Vite docs, which might be more renderer-focused) suitable for a Node.js worker in the main process?

// This?
const worker = new Worker(new URL('./worker.js', import.meta.url))
// Or this?
const worker = new Worker(new URL('./worker.js', import.meta.url), {
  type: 'module'
})

Or is the standard Node.js new Worker(filename) syntax preferred?

Any clarification you could provide on the current best practice for main process workers would be fantastic!

Thanks again for the great work!

hyperknot avatar Apr 27 '25 22:04 hyperknot

electron({
  main: {
    entry: {
      main: 'electron/main.ts',
      worker: 'electron/worker.ts'
    },
  }
})
import path from 'path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workerPath = path.join(__dirname, './worker.js');
this.worker = new Worker(workerPath);

😀 try this.

TuKun33 avatar Aug 08 '25 07:08 TuKun33

Yes, that's the exact solution I settled on!

hyperknot avatar Aug 08 '25 07:08 hyperknot