6

I have a React, Electron app that I wish to be able to access native node modules from the ES6 compiled (using Babel and Webpack).

For example, when I try to require the "fs" node module to access the filesystem I get the following error.

ERROR in ./src/app.js Module not found: Error: Cannot resolve module 'fs' in C:\Users\Propietario-1\Documents\GitHub\AMPLI @ ./src/app.js 1:358-371

But when I required this from a "none compiled" js file it works. I can access the "fs" module.

Any help is appreciated.

Update (2016-08-28):

I ended up requiring the fs module in a script tag on the index.html that calls the bundled script. It works!

<script>
const fs = require('fs');

require('bundle.js');
</script>

After doing this the fs becomes a global variable available to all scripts in the bundle.js. Just make sure to edit your linter options to avoid overwriting it or undef errors.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
ivan quintero
  • 1,240
  • 3
  • 13
  • 22

2 Answers2

7

Electron runs as two processes: the main node process and the renderer process, a bit like a conventional web browser client and server relationship. The renderer process cannot use node modules that are unsuitable for the browser (e.g. fs), because basically it is a browser.

Two methods are provided to communicate between the renderer process and the main process: ipcRenderer and remote. For simple tasks, remote is easier. To use the fs module from your webpacked react project, in the renderer process:

var fs = require('electron').remote.require('fs');
mccleanp
  • 111
  • 1
  • 4
  • Thanks for the answer. I did not know about "remote". However, it still does not seem to work. I required `fs` as you said but it still says that it cannot resolve the module. I opted to require the `fs` module in the index.html file that calls the bundled script as a global variable `const fs = require('fs')` in the meantime. It works. – ivan quintero Aug 28 '16 at 17:47
  • 2
    @mccleanp You saved my effing sanity!! I've been trying to get `odbc` working in an Electron app for 3 days. I have about 100 browser tabs open and this is the first time I've heard about `remote`. And it works. Brilliantly. Looking at your profile, this is your only answer on StackOverflow. Well, I just want to say thank you for taking the time to answer this question. You saved me from losing my mind. :) – Joshua Pinter May 27 '18 at 15:54
0

I ended up requiring the fs module in a script tag on the index.html that calls the bundled script. It works!

<script>
const fs = require('fs');

require('bundle.js');
</script>

After doing this the fs becomes a global variable avaible to all scripts in the bundle.js. Just make sure to edit your linter options to avoid overwriting it or undef errors.

ivan quintero
  • 1,240
  • 3
  • 13
  • 22