問題描述
我正在嘗試在電子中使用網絡工作者.到目前為止,我能夠從渲染器進程中實例化工作進程,但是當我嘗試在工作進程中執行 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.
__dirname
在渲染過程中解析為
__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
等于 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",拱=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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!