问题描述
通常,在Electron应用程序中,您可以在主进程和渲染器进程中同时require
个节点模块:
Typically, in an Electron app, you can require
node modules from both the main process and the renderer process:
var myModule = require('my-module');
但是,如果页面是通过HTTP而不是从本地文件系统加载的,则这似乎不起作用.换句话说,如果我打开一个这样的窗口:
However, this doesn't seem to work if the page was loaded via HTTP instead of from the local filesystem. In other words, if I open a window like this:
win.loadURL(`file://${__dirname}/index.html`);
我可以require
没有问题的节点模块.但是,如果我改为打开一个这样的窗口:
I can require
a node module without problems. But if I instead open a window like this:
win.loadURL(`http://localhost:1234/index.html`);
我不再可以在网页内使用require
节点模块-在网页的控制台中获得了Uncaught Error: Cannot find module 'my-module'
.有什么方法可以在通过HTTP提供的电子页面中使用节点模块?
I no longer can require
node modules inside my web page - I get Uncaught Error: Cannot find module 'my-module'
in the web page's console. Is there any way to use node modules in an Electron page that was served over HTTP?
一个小背景:我的公司正在构建一个应用程序,该应用程序需要能够在Electron外壳内作为Web应用程序和托管.为了使这两种环境更加简单和一致,我的Electron应用程序启动了本地Web服务器,并打开了托管在http://localhost:1234
的应用程序.现在,我希望能够使用 electron-spell-check-provider
.该模块需要在渲染器进程中导入和初始化,因此我试图在网页中使用require('electron-spell-check-provider')
,但这会失败,并显示Cannot find module
错误.
A little context: My company is building an application that needs the ability to be hosted as a web application and inside an Electron shell. To make this simpler and consistent across both environments, my Electron app starts a local web server and opens the app hosted at http://localhost:1234
. Now I'd like the ability to add spell checking/spelling suggestions into the application using electron-spell-check-provider
. This module needs to be imported and initialized inside the renderer process, so I'm trying to require('electron-spell-check-provider')
inside my web page, but this fails with the Cannot find module
error.
推荐答案
最后弄清楚了这一点.在主过程中,找出node_modules目录的绝对路径,如下所示:
Finally figured this out. In the main process, figure out the absolute path to the node_modules directory, as in:
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将此路径转至渲染器进程.最后,您现在可以在渲染器中使用绝对路径:
Now get this path to the renderer process via some IPC. Finally, in the renderer you can now require using an absolute path:
var mymod = require(nodeModDir+'some-valid-module');
对我来说,用电子1.6.7完美地工作.
Works perfectly for me with electron 1.6.7.
这篇关于通过HTTP服务的Electron渲染器进程的require()节点模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!