简体   繁体   中英

Electronjs require usage on renderer process

In electron app, we can require node modules in both renderer and main process. I've realized when I require a module in renderer process' main (html's entry script) it becomes available throughout every file I have. I might not have explained it very clearly so let me give an example.

Consider the following layout for the electron project:

src\
main.js
module1.js
module2.js
index.js
index.html

main.js is the main process of the electron app and index.js is a script loaded inside index.html at the end of its body tag.

Inside index.js I require both module1 and module2 (rest of the file is irrelevant)

const m1 = require('module1')
const m2 = require('module2')

what I realized here is that, inside the module2 I have access to m1 variable now. So I don't need to require module1 again inside the module2 if I need it.

module2:

console.log(m1) // actually shows the m1 that was required in index.js

I feel like I made a mistake trying to write renderer side as if it was a node application. And I failed to find any documentation regarding the general rules while writing the renderer side of the electron app. I know this is a bit indirect question but could you guide me regarding the renderer process layout. Shouldn't I try to separate renderer js file into modules?

You can make use of preload argument in webPreferences while creating the main BrowserWindow.

OR

Try using the remote module of electron ( https://electronjs.org/docs/api/remote )

OR

Access the module in main process, call the functions for the expected outcome and send back the result to the renderer process using IPC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM