如何使用 fs 与电子react?

IT技术 reactjs webpack electron
2021-05-21 17:44:41

我想使用 react+webpack+electron 来构建一个桌面应用程序。如何将fsmodule注入 react 以便我可以使用它来读取本机文件?我有一个组件,例如:

class Some extends Component {
  render() {
    return <div>{this.props.content}</div>
  }
}
export default Some;

entry.js

import React from 'react';
import { render } from 'react-dom';
import Some from './src/some.jsx';

const data = "some content";
/*
 How can I read data by fs module?
 import fs from 'fs' doesn't work here
*/
render(
  <Some content={data} />,
  document.getElementById('app')
);

我使用 webpack 将 js 代码构建到 bundle.js 和 index.html 中

...
<div id="app"></div>
<script src="bundle.js"></script>
...

webpack.config.js

...
plugins: [new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))]
...

我在网上找到了这个配置,因为如果我不添加它,webpack 会报错,但我不知道这是什么意思。

我有一个非常简单的main.js,与电子快速启动的 main.js 相同

我会失去一些重要的东西吗?

如果你能在 github repo 上提供一个现有的例子,那就再好不过了。

3个回答

使用window.require()代替require().

const fs = window.require('fs');

最简单的方法可能是使用webpack-target-electron-renderer,您可以在electron-react-boilerplate 中找到使用它的示例

首先:不要浪费时间使用带有 react 和电子的webpack,react 在构建时已经拥有了自己打包所需的一切。

正如侯赛因在他的回答中所说:

const fs = window.require('fs');

这对我行得通。

此外,在电子的 main.js 上的 webpreferences 上,我设置了以下设置:

webPreferences: {
  preload: path.join(__dirname, 'preload.js'),
  nodeIntegration: true,
  enableRemoteModule: true,
  contextIsolation: false,
  nodeIntegrationInWorker: true,
  nodeIntegrationInSubFrames: true
}

关注电子网站,webpreferences 是一个安全问题,所以我们需要找到一个更好更安全的方法,如here所述