Require () node from an electron rendering process served through HTTP

As a rule, in the Electron application you can require node modules from both the main process and the visualization process:

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

However, this does not work if the page was loaded via HTTP, and not from the local file system. In other words, if I open the window as follows:

 win.loadURL(`file://${__dirname}/index.html`); 

I can require a node module without problems. But if I open the window like this instead:

 win.loadURL(`http://localhost:1234/index.html`); 

I can no longer require node modules inside my web page - I get Uncaught Error: Cannot find module 'my-module' in the web page console. Is there a way to use node modules on an Electron page that has been transmitted via HTTP?


A small context: my company is creating an application that should be hosted as a web application and inside the Electron shell. To make this easier and more consistent in both environments, the Electron application launches the local web server and opens the application hosted at http://localhost:1234 . Now I need the ability to add electron-spell-check-provider checker / electron-spell-check-provider checker applications to the application using electron-spell-check-provider . This module needs to be imported and initialized inside the rendering process, so I'm trying to require('electron-spell-check-provider') on my web page, but this is not with Cannot find module error.

+5
source share
2 answers

Finally figured it out. In the main process, define 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); 

Now get this path to the rendering process through some IPC. Finally, in the renderer you can now use the absolute path:

 var mymod = require(nodeModDir+'some-valid-module'); 

Works well for me with electron 1.6.7.

+1
source

Had a similar problem. Try executing renderer.js via HTTP in index.html , e.g.

  <script src="/renderer.js"></script> </body> 

Then, according to the docs , load your module by adding a remote control after a request in the renderer. js .

var spellCheck = require('electron-spell-check-provider').remote;

-1
source

All Articles