简体   繁体   English

从 main.js 外包功能

[英]Outsource functionality from main.js

I've started building an electron application from scratch.我已经开始从头开始构建一个 electron 应用程序。 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.到目前为止,我可以通过在main.js中插入所有逻辑来修改mainWindow ,但我想将逻辑保存在单独的文件中。 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.使用ng build --prod && electron. throws:抛出:

Cannot read property 'getName' of undefined.无法读取未定义的属性“getName”。

Thanks in advance;)提前致谢;)

Please import your js as const test = require('./test') and then use test.getName() in your main js file.请将您的 js 导入为const test = require('./test') ,然后在您的主 js 文件中使用test.getName() when calling const {test} is trying to import the test object in the at relevant file.当调用const {test}试图在 at 相关文件中导入test object 时。 You can read more about that from this answer您可以从此答案中阅读更多相关信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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