簡體   English   中英

從 main.js 外包功能

[英]Outsource functionality from main.js

我已經開始從頭開始構建一個 electron 應用程序。 到目前為止,我可以通過在main.js中插入所有邏輯來修改mainWindow ,但我想將邏輯保存在單獨的文件中。 不幸的是我無法正確導入它們,所以幫助會很好..

// 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;

使用ng build --prod && electron. 拋出:

無法讀取未定義的屬性“getName”。

提前致謝;)

請將您的 js 導入為const test = require('./test') ,然后在您的主 js 文件中使用test.getName() 當調用const {test}試圖在 at 相關文件中導入test object 時。 您可以從此答案中閱讀更多相關信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM