在电子工进程中不能要求使用node_modules [英] Cannot require node_modules in electron worker process

查看:39
本文介绍了在电子工进程中不能要求使用node_modules的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在电子领域使用网络工作者.到目前为止,我可以从渲染器进程实例化工作进程,但是当我尝试在工作进程中执行 require('some_module')时,该进程崩溃并显示错误.

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.

找不到模块'some_module'.

cjs加载器显然找不到我的模块.但是,当我在渲染器进程中进行相同的 require 调用时,我就能够 require 该模块.

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.

我已经按照此处所述的所有步骤进行操作.另外,我还设置了 nodeIntegrationInWorker:true 选项,并且可以毫无问题地对 fs 之类的节点内置模块进行 require 调用.

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.

    呈现过程中的
  1. __ dirname 解析为

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

据我所读,require函数应该能够在 renderer node_modules 目录中找到我的模块.>工人目录

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

快速查看工作程序中的全局 process ,可以发现 process.type 等于 worker ,而 process.argv [1] 等于-type = renderer ,我觉得很奇怪.

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.


:电子版本="4.0.0",平台="win32",arch ="x64",节点版本="v10.11.0"


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

在这方面的任何帮助将不胜感激.

Any help in this regard would be appreciated.

推荐答案

好.作为解决方法,我使用它.

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.

这篇关于在电子工进程中不能要求使用node_modules的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆