在电子工作进程中不能要求 node_modules

Cannot require node_modules in electron worker process(在电子工作进程中不能要求 node_modules)

本文介绍了在电子工作进程中不能要求 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 在渲染过程中解析为

  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

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

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

快速查看 worker 中的 process 全局,发现 process.type 等于 workerprocess.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",拱=x64",节点版本=v10.11.0"


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

我们将不胜感激.

推荐答案

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在电子工作进程中不能要求 node_modules

基础教程推荐