0

I've started building an electron application from scratch. So far I can modify the mainWindow by inserting all the logic in main.js, but I'd like to keep the logic in separate files. Unfortunatly I fail to import them correctly, so help would be nice..

// main.js
const { app, BrowserWindow, Menu, dialog } = require('electron');
const fs = require('fs');

const { test } = require('./test'); // test module to be imported

let win;

function createWindow() {
  win = new BrowserWindow({
    icon: `file://${__dirname}/dist/text-editor/favicon.ico`,
    webPreferences: {
      nodeIntegration: true
    }
  });
  win.maximize();

  win.loadURL(`file://${__dirname}/dist/text-editor/index.html`);

  win.webContents.openDevTools();

  //menu bar
  const template = getTemplate();
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);


  win.on('closed', function () {
    win = null;
  });

  console.log(test.getName()); // throws error
}

// create window on electron init
app.on('ready', createWindow);

// quit when all windows are closed
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  if (win === null) {
    createWindow();
  }
});

function getTemplate() {...} // for example move this method to new file
// test.js
const getName = () => {
  return "Tom";
};

module.exports.getName = getName;

Running this code with ng build --prod && electron . throws:

Cannot read property 'getName' of undefined.

Thanks in advance ;)

Wolf
  • 9,679
  • 7
  • 62
  • 108
Lecagy
  • 489
  • 2
  • 10

1 Answers1

0

Please import your js as const test = require('./test') and then use test.getName() in your main js file. when calling const {test} is trying to import the test object in the at relevant file . You can read more about that from this answer

namila007
  • 1,044
  • 9
  • 26