Skip to content

Correct way of using workers in main #275

@hyperknot

Description

@hyperknot

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:
#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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions