如何在React,ES6,Electron App上使用本机节点模块? [英] How to use Native Node Modules on a React, ES6, Electron App?

查看:42
本文介绍了如何在React,ES6,Electron App上使用本机节点模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React,Electron应用程序,希望能够从已编译的ES6(使用Babel和Webpack)访问本机节点模块.

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).

例如,当我尝试要求"fs"节点模块访问文件系统时,出现以下错误.

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

但是当我从未编译"的js文件中要求使用此文件时,它可以工作.我可以访问"fs"模块.

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

感谢您的帮助.

更新(2016-08-28):

我最终需要在index.html上的脚本标签中的 fs 模块中调用捆绑的脚本.可行!

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>

完成此操作后, fs 成为一个全局变量,可供 bundle.js 中的所有脚本使用.只需确保编辑您的linter选项,以免覆盖它或 undef 错误.

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.

推荐答案

电子作为两个进程运行:主节点进程和渲染器进程,有点像常规的Web浏览器客户端和服务器关系.渲染器进程不能使用不适合浏览器的节点模块(例如 fs ),因为基本上它是浏览器.

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.

提供了两种在渲染器进程和主进程之间进行通信的方法: ipcRenderer remote .对于简单的任务,远程操作更容易.要在Webpacked react项目中使用 fs 模块,请在渲染器过程中:

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

这篇关于如何在React,ES6,Electron App上使用本机节点模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆