我正在尝试创建一个小型 React 应用程序来捕获和设置全局快捷方式,该快捷方式将用于显示和隐藏 Electron 应用程序窗口。然而,我被卡住了,因为当我尝试从 React 组件内部使用 ipcRender 时,抛出了以下错误。
Uncaught Error: Cannot find module "fs"
我正在使用 Webpack 来捆绑我的 JS 并编译 JSX,并使用 ES6 语法来导入 Electron 和 ipcRender,如您在下面我的组件代码中所见。
import React from "react";
import electron, { ipcRenderer } from 'electron';
var event2string = require('key-event-to-string')({});
export default React.createClass({
getInitialState: function() {
return {shortcut: this.props.globalShortcut[0]};
},
handleOnKeyDown:function(e){
e.preventDefault();
var keys = event2string(e);
this.setState({shortcut:keys});
this.props.globalShortcut.splice(0, 1);
this.props.globalShortcut.push(keys);
},
handleOnKeyUp:function(){
this.refs.shortcutInput.value = this.state.shortcut;
this.refs.shortcutInput.blur();
ipcRenderer.send('set-new-shortcut', this.props.globalShortcut);
},
handleOnFocus:function(){
this.refs.shortcutInput.value = '';
},
render() {
return (
<div id="settings-container">
<h1>The show/hide shortcut is "{this.state.shortcut}"</h1>
<form role="form">
<input type="text" ref="shortcutInput" placeholder="Create new shortcut" onFocus={this.handleOnFocus} onKeyDown={this.handleOnKeyDown} onKeyUp={this.handleOnKeyUp} className="form-control form-field"/>
</form>
</div>
);
}
});
我尝试了不同的解决方案,例如将 node-loader 和 json-loader 添加到我的 Webpack 文件中,添加 Node fs 设置为“空”的对象,包括一个插件,告诉 Webpack 忽略 fs 和 ipc 并安装fs 通过 npm。我无法让他们中的任何一个工作。
不幸的是,我对 Webpack 或 ES6 语法的了解不够,无法弄清楚发生了什么,而且我尝试过的大多数解决方案都是在“粘贴希望”时尚。因此,如果有人能用通俗易懂的语言解释发生了什么,我将能够挖掘更多内容。
下面是我当前的 Webpack 文件。
var webpack = require('webpack');
module.exports = {
context: __dirname + '/src/js',
entry: "./index.js",
output: {
filename: 'bundle.js',
path: __dirname + '/build',
publicPath: 'http://localhost:8080/build/'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query:{presets:['es2015','react']} },
{ test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }
]
},
// Don't know if below is working, 'Uncaught Error: Cannot find module "fs"' error still thrown when trying to import electron
plugins: [
new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))
],
// Don't know if below is working, 'Uncaught Error: Cannot find module "fs"' error still thrown when trying to import electron
node: {
fs: 'empty'
}
};
最佳答案
您需要在您的 Webpack 配置中设置 target: 'electron-renderer'
,如果之后您仍然有问题,请查看 https://github.com/chentsulin/electron-react-boilerplate
关于javascript - 从 React 组件内部使用 Electron ipcRenderer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332546/