Skip to content
Advertisement

import menu to browser window by “require” function

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.

JavaScript

main.js

JavaScript

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.”

Advertisement

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

JavaScript

main.js

JavaScript

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement