Electron App - Divide main process into several files and share variable

Viewed 435

I'm developing an app with Electron, but I have a problem to exchange a variable between several files.

In my main.js, I create an RxDB database that is used for my entire project. At this level, I also create handlers allowing the communication between the main process and the render process via IPC. These handlers call various Classes that perform various processes including database insertions, modifications, etc.

In my opinion, I haven't found an efficient way to transmit my variable containing my database to my classes.

Ideally, I should be able to call this database variable (declared in main.js) at any time from any class. I can't use the IPC system because my returned variable must not be a JSON but absolutely an RxDatabase object.

Here is a very simplified diagram of my main process:

Diagram of my main process

Currently, to share my database variable to my classes:

  • I declare the variable in main.js
  • I transmit the variable in the handlers
  • I transmit the variable to my classes in a static variable class

Although ugly, this system works. But I think there is a more correct way to do it. Also, it becomes difficult to preserve this variable when a class calls one or more instances of external classes.

Thanks.

2 Answers

A simple export / import is enough.

Previously, I tried to export my variable from main.js but when I tried to use export {database}, I had an Unexpeted token export error.So I had assumed that it would be impossible for me to export a variable from main.js for some obscure reasons specific to Electron.

In fact, you just need to use a ES5 syntax, that way exports.database = database in main.js. Then, you can import this variable in any file of your main process.

Thanks @Luke for his answer.

You can use exports.variable = variable and then import { variable } from 'file' in the other file.

Related