3
votes

Question

I'm trying to use web workers in electron. So far I'm able to instanciate the worker process from the renderer process, but when I try to do a require('some_module') in the worker process the process crashes with the error.

Cannot find module 'some_module'.

The cjs loader cannot find my module apparently. But when I make the same require call from the renderer process, I'm able to require the module.

I've followed all the steps mentioned here. Also I've set the optionnodeIntegrationInWorker: true and I can make require calls to node inbuilt modules like fs with no problems.


A few observations

  1. __dirname in the rendered process resolves to

    root/node_modules/electron/dist/resources/electron.asar/renderer

    and in the worker process resolves to

    root/node_modules/electron/dist/resources/electron.asar/worker

    as far as I've done the reading the require function should be able to find my module in the node_modules dir which is parent to both the renderer and worker dir

  2. A quick look at the process global in the worker reveals that process.type is equals worker while process.argv[1] is equals --type=renderer which I find strange.


Meta: Electron version = "4.0.0", platform = "win32", arch = "x64", node version = "v10.11.0"

Any help in this regard would be appreciated.

1
Having the same issue. Electron is awful. Very poor documentation. - m4heshd

1 Answers

0
votes

Ok. As a workaround, I use this.

    const paths = [
        path.join(process.resourcesPath, 'app.asar', 'node_modules'),
        path.join(process.resourcesPath, 'app', 'node_modules'),//when asar is disabled
        process.resourcesPath.replace(/electron[\\/]dist[\\/]resources/g, '')
    ];

    paths.map((path) => {
        global.require.main.paths.push(path);
    });

The above snippet manually adds the paths node looks to resolve the required module.