In an electron app I have
exports.sayWord = function(){
console.log("some word")
};
in main.js. Now, in renderer.js
, I have
const main = require('./main.js');
But when I run the app and open the devtools I have the error:
Uncaught TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (/home/sean/elecapp/main.js:47:4)
at Object.<anonymous> (/home/sean/elecapp/main.js:70:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/sean/elecapp/renderer.js:20:14)
Line 47 is:
app.on('ready', createWindow);
but this does not make sense because the window is created, so obviously electron knew what app
an createWindow
were. I suspect that the problem has something to do with the fact that I am requiring main.js
because I put the function sayWord
in other files and when I required those nothing was wrong.
The reason you get the error is because the main-process and the renderer-process do not have access to the same modules. For example app
can be accessed in the main-process directly via const {app} = require("electron")
, but in the renderer you can only access a proxy object via const {app} = require("electron").remote
. But you shouldn't use remote.app
either to fix your problem. If you were to modify your main.js script to run on both main-process and renderer-process, you would probably create a loop of creating new windows!
You should outsource the sayWord
to a different file. If you plan to send data between main and renderer, then I would suggest to use ipcMain and ipcRenderer instead.