通常,在Electron应用程序中,您可以从主进程和渲染器进程中对 Node 模块进行require编码:

var myModule = require('my-module');

但是,如果页面是通过HTTP而不是从本地文件系统加载的,则这似乎不起作用。换句话说,如果我打开一个这样的窗口:
win.loadURL(`file://${__dirname}/index.html`);

我可以require一个没有问题的 Node 模块。但是,如果我改为打开一个这样的窗口:
win.loadURL(`http://localhost:1234/index.html`);

我不再可以在网页内添加require Node 模块-我在网页的控制台中获得Uncaught Error: Cannot find module 'my-module'。有什么方法可以在通过HTTP提供的 Electron 页面中使用 Node 模块吗?

一个小背景:我的公司正在构建一个应用程序,该应用程序需要能够作为Web应用程序托管在Electron Shell内。为了使这两种环境更加简单一致,我的Electron应用程序启动了本地Web服务器,并打开了在http://localhost:1234托管的应用程序。现在,我希望能够使用 electron-spell-check-provider 将拼写检查/拼写建议添加到应用程序中。该模块需要在渲染器进程中导入和初始化,因此我正在尝试在网页内添加require('electron-spell-check-provider'),但是此操作因Cannot find module错误而失败。

最佳答案

终于想通了。在主过程中,找出到node_modules目录的绝对路径,如下所示:

var nodeModDir = require.resolve('some-valid-module');
var dirnm      = 'node_modules';
var pos = nodeModDir.lastIndexOf(dirnm);
if(pos != -1)
    nodeModDir = nodeModDir.substr(0, pos+dirnm.length+1);

现在,通过某些IPC获得通往渲染器过程的路径。最后,在渲染器中,您现在可以要求使用绝对路径:
var mymod = require(nodeModDir+'some-valid-module');

Electron 1.6.7对我来说非常有效。

关于node.js - 通过HTTP服务的Electron渲染器进程的require() Node 模块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39370530/

10-11 20:42
查看更多