GoogleChromeLabs / worker-plugin

👩‍🏭 Adds native Web Worker bundling support to Webpack.
https://npm.im/worker-plugin
Apache License 2.0
1.91k stars 79 forks source link

vue-cli-plugin-electron-builder #77

Closed MehrdadKhnzd closed 4 years ago

MehrdadKhnzd commented 4 years ago

Hey there! I'm trying to use some Node.js modules in a Web Worker in an Electron app written in Vue. The problem is when I want to import or require those Node.js modules (including things like serialport and stuff) I get an error and I can't use any of them. I've read it here and there and I know it is something known, but I can't really figure out what's going on cause I have very little experience with both Electron and Webpack. By the way, any help will be really appreciated!

Used Vue plugin Github page: https://github.com/nklayman/vue-cli-plugin-electron-builder Link to another issue trying to explain this: #75

developit commented 4 years ago

Hi - Electron doesn't expose Node modules in Workers. There's nothing a plugin or build tool can do to address this, it's a limitation of Electron itself.

eschirtz commented 4 years ago

Per the electron docs, https://www.electronjs.org/docs/tutorial/multithreading#multi-threaded-nodejs, node is actually available in workers with the nodeIntegrationInWorker flag set true. I'm running into similar issues as @MehrdadKhnzd . Maybe we can re-open?

haroldiedema commented 3 years ago

I'm experiencing the same issue, but I'm unsure if this is a problem with the vue-cli-plugin-electron-builder package, or this one.

Even with the nodeIntegrationInWorker flag enabled, this plugin seems to ignore it. The whole discussion about worker_threads is completely irrelevant to WebWorkers imho.

haroldiedema commented 3 years ago

@MehrdadKhnzd - Here is a very nasty hack to make it work in Electron (since the native require method is always available when nodeIntegrationInWorker is enabled):

        const r = global['req' + 'uire'];

        const fs   = r('fs'),
              path = r('path');

// You can now use fs.existsSync() inside the worker.
console.log(fs.existsSync('hello-world.txt'));

The whole point of this 'hack' is to trick Webpack into thinking you're not actually using the require function, so it'll stay away trying to 'transpile' your code.... Its disguisting to use, but at least it works...for now.

2xAA commented 3 years ago

Thanks for the hack, @haroldiedema. This issue should be re-opened for sure, but the above does work.