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

Can't load worker (modulePath) with in ES module scope

Open clemp6r opened this issue 6 months ago • 3 comments

Describe the bug

Hi, I'm trying to load a worker from the main process with an ESM ("type": "module") project, using the following syntax:

import workerPath from "./native-worker?modulePath";

...

When starting the app in dev mode, I get:

App threw an error during load
ReferenceError: __dirname is not defined in ES module scope

Note: using a ?nodeWorker style import seem to work, but apparently it's not the recommended way to go (source).

Thanks

Electron-Vite Version

4.0.0

Electron Version

36.5.0

Vite Version

7.0.4

Validations

clemp6r avatar Jul 11 '25 08:07 clemp6r

This might be a bug. CJS syntax compatibility isn't working in the worker. You can use the following ESM syntax instead.

import.meta.dirname

alex8088 avatar Jul 11 '25 17:07 alex8088

There is no __dirname code in my worker, it's generated by electron-vite.

// worker.ts
import { parentPort } from "worker_threads";

parentPort.postMessage("It works!");
//  worker consumer
import workerPath from "./worker?modulePath";

...
// generated index.js
...
const workerPath = join$1(__dirname, "./worker-BsYDk9WK.js");
...

clemp6r avatar Jul 15 '25 07:07 clemp6r

Same issue here. [email protected] & [email protected]

yanglee2421 avatar Oct 06 '25 12:10 yanglee2421

fixed, electron-vite 5

alex8088 avatar Dec 08 '25 07:12 alex8088