在电子工作过程中不需要node_modules



问题

我正在尝试在电子中使用网络工作者。到目前为止,我能够从渲染器进程中实例化工作进程,但是当我尝试在工作进程中执行require('some_module')时,进程崩溃并出现错误。

找不到模块"some_module"。

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

我已经按照这里提到的所有步骤进行操作。此外,我nodeIntegrationInWorker: true设置了选项,我可以毫无问题地对节点内置模块(如fs)进行require调用。


几点意见

  1. 呈现过程中__dirname解析为

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

    并在工作进程中解析为

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

    就我完成的读取而言,require函数应该能够在node_modules目录中找到我的模块,该模块是渲染器和工作线程目录的父级

  2. 快速浏览一下工人中的全局process会发现process.type等于workerprocess.argv[1]等于--type=renderer我觉得很奇怪。


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

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

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

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);
});

上面的代码片段手动添加了路径节点外观以解析所需的模块。

你不需要做上述操作。只需从app.asar的node_modules中执行要求:

const myModule = require(process.resourcesPath + '/app.asar/node_modules/' + 'modulename');

以后谢谢我;

最新更新