問(wèn)題描述
我正在嘗試在電子中使用網(wǎng)絡(luò)工作者.到目前為止,我能夠從渲染器進(jìn)程中實(shí)例化工作進(jìn)程,但是當(dāng)我嘗試在工作進(jìn)程中執(zhí)行 require('some_module')
時(shí),進(jìn)程會(huì)因錯(cuò)誤而崩潰.
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 加載器顯然找不到我的模塊.但是,當(dāng)我從渲染器進(jìn)程進(jìn)行相同的 require
調(diào)用時(shí),我能夠 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.
我已按照此處中提到的所有步驟進(jìn)行操作.此外,我還設(shè)置了選項(xiàng)nodeIntegrationInWorker: true
,我可以毫無(wú)問(wèn)題地對(duì) fs
等節(jié)點(diǎn)內(nèi)置模塊進(jìn)行 require
調(diào)用.
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.
__dirname
在渲染過(guò)程中解析為
__dirname
in the rendered process resolves to
root/node_modules/electron/dist/resources/electron.asar/renderer
并且在工作進(jìn)程中解析為
and in the worker process resolves to
root/node_modules/electron/dist/resources/electron.asar/worker
據(jù)我閱讀,require 函數(shù)應(yīng)該能夠在 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
全局,發(fā)現(xiàn) process.type
等于 worker
而 process.argv[1]
等于 --type=renderer
我覺(jué)得很奇怪.
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.
<小時(shí)>
元:電子版本=4.0.0",平臺(tái)=win32",拱=x64",節(jié)點(diǎn)版本=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);
});
以上代碼片段手動(dòng)添加路徑節(jié)點(diǎn)查找以解析所需模塊.
The above snippet manually adds the paths node looks to resolve the required module.
這篇關(guān)于在電子工作進(jìn)程中不能要求 node_modules的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!