Here is my main (index.js) file:
const { app, BrowserWindow } = require("electron")
var mainWindow = null
app.on("ready", () => {
mainWindow = new BrowserWindow({
"width": 500,
"height": 500,
"webPreferences": {
"nodeIntegration": true,
"contextIsolation": false
}
})
mainWindow.loadFile("src/html/welcome.html")
})
Now, I cannot use import/exports.
Whenever I am adding an export statement below the above code, it gives an error saying Uncaught TypeError: Cannot read properties of undefined (reading 'on')
If I remove the export/import lines, it works fine, as expected
(index.js)
const { app, BrowserWindow } = require("electron")
var mainWindow = null
app.on("ready", () => {
mainWindow = new BrowserWindow({
"width": 500,
"height": 500,
"webPreferences": {
"nodeIntegration": true,
"contextIsolation": false
}
})
mainWindow.loadFile("src/html/welcome.html")
})
module.exports.updateFunction = (_name) => {
console.log(_name)
}
another.js
const { updateFunction } = require("../../index");
updateFunction("Hellow")
What I think is happening here is that you are creating a circular dependency for yourself. It might help whe you try to follow the path the module loader is taking (or trying to take) when loading your modules:
index.js
another.js loads your entry point module index.jsAt this point index.js is not completely loaded as all its dependencies have to load first. The circular dependency leaves the module loader in an undefined state, which depending on it's implementation can result in all sorts of errors. Usually it's along the lines of
some.stuff is not a function
Cannot read property `XXX` of undefined
`XXX` does not exist
undefined index `#` of `XXX`
There are ways to get around these errors, but the easiest approach is to avoid circular dependencies. In your case it would probably be easiest to create a module that both your another.js and your index.js can import from:
// someModule.js
const { app, BrowserWindow } = require("electron")
let mainWindow = null
app.on("ready", () => {
mainWindow = new BrowserWindow({
"width": 500,
"height": 500,
"webPreferences": {
"nodeIntegration": true,
"contextIsolation": false
}
})
mainWindow.loadFile("src/html/welcome.html")
})
// you can export mainWindow if you need it
module.exports.mainWindow = mainWindow;
module.exports.updateFunction = (_name) => {
console.log(_name)
}
// index.js
const { mainWindow } = require('someModule');
// another.js
const { updateFunction } = require("../../someModule");
updateFunction("Hellow")
I would also recommend using Es6-style imports and exports as they are much easier to comprehend, but that's a different story.