import menu to browser window by “require” function

Tags: , , ,



I am working on a electron demo by following this tutorial.

just wondering what happened in the require line of code.

./menu/mainmenu.js defines the menu items.

const {Menu} = require('electron')
const electron = require('electron')
const app = electron.app

const template = [
  {
    label: 'Edit',
    submenu: [
      {
        role: 'undo'
      },
      {
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        role: 'cut'
      },
      {
        role: 'copy'
      },
      {
        role: 'paste'
      },
      {
        role: 'pasteandmatchstyle'
      },
      {
        role: 'delete'
      },
      {
        role: 'selectall'
      }
    ]
  }
]

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

main.js

const { app, BrowserWindow, ipcMain } = require('electron');
let win;

function createWindow () {
  win = new BrowserWindow({
    width: 880,
    height: 660,
    webPreferences: {
      nodeIntegration: true
    }
  })
  // and load the index.html of the app.
  win.loadFile('index.html')

  require('./menu/mainmenu') //does this line copied the whole mainmenu.js file?
}

does the require('./menu/mainmenu') copy whole file into main.js?

Or imported some modules? In the mainmenu.js file There is no export keyword.

according to the node.js documentation,

“The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.”

Answer

require here doesn’t copy file around (unlike c++ #include)

Instead it execute the file and return the exported items (if any)


Since there is no export in './menu/mainmenu' when you call require, it simply executed that file.

The problem with this approach is require would only process that file once*, the proper way is actually export something which can be used multiple times.


example:

./menu/mainmenu.js

//...
const menu = Menu.buildFromTemplate(template)
export default ()=>Menu.setApplicationMenu(menu)

main.js

const { app, BrowserWindow, ipcMain } = require('electron');

let win;

function createWindow () {
  //...

  const setmenu = require('./menu/mainmenu') // you can put this at top, too
  setmenu();

  // or you can execute it inline
  // require('./menu/mainmenu')()
}

note: you may need https://www.npmjs.com/package/babel-plugin-add-module-exports or some workaround to make require and default export works together.


*the problem with this is you cannot really rely on it to work everytime, e.g. change menu from A -> B -> A , the second require('A') would silently do nothing.



Source: stackoverflow