How to use Native Node Modules on a React, ES6, Electron App?

和自甴很熟 提交于 2021-01-27 04:41:50

问题


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.


回答1:


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');



回答2:


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.



来源:https://stackoverflow.com/questions/39182876/how-to-use-native-node-modules-on-a-react-es6-electron-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!