Newbie: Placing "native" menu in a separate file (not main.js) - the proper way?


I’m trying to build a “native” menu in the main process and to keep “things” separated I would like to have the menu construction source code located in another file, say ./app/menu.js (path relative to where main.js is placed).

It seems I can get it to work without issues, but I haven’t fully understood what is going on.

In main.js I have:

const electron = require(‘electron’);
const {app, BrowserWindow} = require(‘electron’);
… stuff left out here …
var menu = require(’./app/menu.js’); // question 3.

In menu.js I have :

const {app, BrowserWindow} = require(‘electron’); // question 1.
const {Menu} = require(‘electron’);
const template = [
… stuff left out here …
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu) = menu; // question 2.

Question 1.
If I leave out the line ending with “// question 1” I get a Javascript error:

A JavaScript error occurred in the main process.
Uncaught Exception:
ReferenceError: app is not defined.

Is it correct to include line ending with “// question 1” in menu. js?
It seems I’m defining the constant “app” twice?
But it seems main.js and menu.js live somewhat separate lives?

Question 2.
Is the line ending with “// question 2” needed?
Can you think of situations where I would need this?

Question 3
Related to question 2. .
Can you think of situations where I would need the part "var menu = " in line ending with “// question 3”?

Kind regards,


Guess I found the answer to question 1:
RTFM ;o)



Modules are cached after the first time they are loaded. This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file. Multiple calls to require(‘foo’) may not cause the module code to be executed multiple times.