【问题标题】:how can I use fs in react with electron?如何使用 fs 与电子反应?
【发布时间】:2016-05-27 12:01:07
【问题描述】:

我想使用 react+webpack+electron 构建一个桌面应用程序。如何将fs 模块注入到 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,它和electron-quick-start的main.js一样

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

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

【问题讨论】:

    标签: reactjs webpack electron


    【解决方案1】:

    使用window.require() 而不是require()

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

    【讨论】:

    • 这帮助我解决了问题!非常感谢!我已经被这个问题困扰了 3 天,我什至在使用 webpack 时只会遇到更多错误而不是正确的解决方案。
    【解决方案2】:

    最简单的可能是使用webpack-target-electron-renderer,你可以在electron-react-boilerplate找到使用它的例子。

    【讨论】:

      【解决方案3】:

      首先:不要在 webpack 上浪费时间,使用 react 和 electron,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 所述

      【讨论】:

      • webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, enableRemoteModule: true, contextIsolation: false, nodeIntegrationInWorker: true, nodeIntegrationInSubFrames: true } 这个帮我
      • contextIsolation: falsewindow.require 是它为我工作所必需的。
      猜你喜欢
      • 1970-01-01
      • 2018-06-08
      • 2021-01-25
      • 2020-10-10
      • 2020-02-16
      • 2021-12-24
      • 2018-04-01
      • 2016-08-08
      • 2021-10-22
      相关资源
      最近更新 更多