caibirdme
caibirdme

Reputation: 501

how can I use fs in react with electron?

I want use react+webpack+electron to build a desktop app.How can I inject fs module into react so that I can use it to read native files? I have a component such as:

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

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

I use webpack to build js codes into a bundle.js,and in index.html

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

In webpack.config.js:

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

I find this config on the internet because if I don't add it the webpack will report error,but I don't know how this means.

And I have a very easy main.js which is the same as electron-quick-start's main.js

Do I lose some important things?

It can't be better if u can provide a existed example on github repo.

Upvotes: 19

Views: 28529

Answers (4)

iiromutikainen
iiromutikainen

Reputation: 56

Since Electron 12 contextIsolation is true by default and it is recommended.

So with nodeIntegration: true and contextIsolation: true

First see https://www.electronjs.org/docs/latest/tutorial/context-isolation/

FIRST in preload.js expose the require function to renderer:

require: (callback) => window.require(callback)

THEN in renderer you can import it by:

const { myAPI } = window
const fs = myAPI.require('fs')

Upvotes: 1

klys
klys

Reputation: 362

First of all: Don't lost time with webpack with react and electron, react already have everything it need itself to pack themself when building.

As Hossein say in his answer:

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

that works for me.

Additionally on webpreferences on the main.js of electron i set this settings:

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

following the electron website that webpreferences are a security problem so we need to found a better a more safer ways as described here

Upvotes: 3

Hossein
Hossein

Reputation: 4559

use window.require() instead of require().

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

Upvotes: 21

Vadim Macagon
Vadim Macagon

Reputation: 14847

The easiest thing to do is probably to use webpack-target-electron-renderer, you can find examples of using it in electron-react-boilerplate.

Upvotes: 5

Related Questions