Add create react app to a project created by electron. Electronic cannot be used in react
When using require (‘Electronic ‘) in react, it will report
uncaught type error: fs.existssync is not a function at getelectronpath (index. JS: 8)
because the module of node.js cannot be used in react.
therefore, Baidu has proposed the following scheme:
Create the render.js file
global.electron = require('electron');
Modify the main.js file
Modify the entry code of creating browser and add preload configuration item. Render.js as preload file
win = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
javascript: true,
plugins: true,
nodeIntegration: true,
webSecurity: false,
preload: path.join(__dirname, '../public/renderer.js')
}
})
in the react component, use electron
const electron = window.electron as follows
Because you want to use process communication, you can directly write this in the rendering process:
const ipcRenderer = window.electron.ipcRenderer;
At this time, there is no error in typeerror: fs.existssync is not a function
when fs.existssync is not a function error is no longer reported, a new error starts
Uncaught ReferenceError: require is not defined
I don’t know what’s going on. I’m just looking at my main.js. The node environment shouldn’t report an error that doesn’t have the definition of require. So Baidu has made a lot of changes, so I modified several of my files:
index.html:
<script>
window.electron = require('electron');
</script>
<div id="root"></div>
main.js:
win = new BrowserWindow({
width: 1000,
height: 800,
webPreferences: {
nodeIntegration: true,
}
})
In the rendering process that references this:
getName = (e) =>{
e.preventDefault()
const ipcRenderer = window.electron.ipcRenderer;
// console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
// ipcRenderer.on('asynchronous-reply', (event, arg) => {
// console.log(arg) // prints "pong"
// })
ipcRenderer.send('asynchronous-message', 'ping')
// ipcRenderer.send('get-reader-list', '')
}
And then you can
npm run electron
It’s working perfectly
Happy ~ ~ ~ thank you for helping me@ The way of heaven rewards diligence,
although small water drops are insignificant, they can gather little by little into the sea! Take your time. Sometimes when you feel it’s hard to walk, you’re going uphill. Come on
later, a new project was created, and it was found that both methods were feasible and could be tried many times