I'm trying to use Node modules (in this example, fs) in my renderer processes, like this:
// main_window.js
const fs = require('fs')
function action() {
console.log(fs)
}
Note: The action function gets called when I press a button in my main_window.
But this gives an error:
Uncaught ReferenceError: require is not defined
at main_window.js:1
I can solve this issue, as suggested by this accepted answer, by adding these lines to my main.js when initializing the main_window:
// main.js
main_window = new BrowserWindow({
width: 650,
height: 550,
webPreferences: {
nodeIntegration: true
}
})
But, according to the docs, this isn't the best thing to do, and I should instead, create a preload.js file and load these Node modules there and then use it in all of my renderer processes. Like this:
main.js:
main_window = new BrowserWindow({
width: 650,
height: 550,
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
preload.js:
const fs = require('fs')
window.test = function() {
console.log(fs)
}
main_window.js:
function action() {
window.test()
}
And it works!
Now my question is, isn't it counter-intuitive that I should write most of the code of my renderer processes in preload.js (Because only in preload.js I have access to Node modules) and then merely call the functions in each renderer.js file (for example here, main_window.js)? What am I not understanding here?
Things have progressed quickly in Electron, causing some confusion. The latest idiomatic example (as best as I can determine after much gnashing of teeth) is:
main.js
app.whenReady().then(() => {`
let mainWindow = new BrowserWindow({`
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true
},
width:640,
height: 480,
resizable: false
})
... rest of code
preload.js
const { contextBridge, ipcRenderer} = require('electron')
contextBridge.exposeInMainWorld(
'electron',
{
sendMessage: () => ipcRenderer.send('countdown-start')
}
)
renderer.js
document.getElementById('start').addEventListener('click', _ => {
window.electron.sendMessage()
})