【发布时间】:2018-11-26 13:37:24
【问题描述】:
我正在开发一个 Electron 应用程序,我的目标是“拆分”index.js(主进程)文件。目前,我已将与菜单栏相关和与触控栏相关的代码放入两个单独的文件中,menu.js 和 touchBar.js。这两个文件都依赖于一个名为redir 的函数,该函数位于index.js 中。每当我尝试在我的菜单栏中激活 click 事件时 - 它依赖于 redir - 我都会收到错误消息:
TypeError: redir is not a function。这也适用于我的 Touch Bar 代码。
这是我的(截断的)文件:
index.js
const { app, BrowserWindow } = require('electron'); // eslint-disable-line
const initTB = require('./touchBar.js');
const initMenu = require('./menu.js');
...
let mainWindow; // eslint-disable-line
// Routing + IPC
const redir = (route) => {
if (mainWindow.webContents) {
mainWindow.webContents.send('redir', route);
}
};
module.exports.redir = redir;
function createWindow() {
mainWindow = new BrowserWindow({
height: 600,
width: 800,
title: 'Braindead',
titleBarStyle: 'hiddenInset',
show: false,
resizable: false,
maximizable: false,
});
mainWindow.loadURL(winURL);
initMenu();
mainWindow.setTouchBar(initTB);
...
}
app.on('ready', createWindow);
...
menu.js
const redir = require('./index');
const { app, Menu, shell } = require('electron'); // eslint-disable-line
// Generate template
function getMenuTemplate() {
const template = [
...
{
label: 'Help',
role: 'help',
submenu: [
{
label: 'Learn more about x',
click: () => {
shell.openExternal('x'); // these DO work.
},
},
...
],
},
];
if (process.platform === 'darwin') {
template.unshift({
label: 'Braindead',
submenu: [
...
{
label: 'Preferences...',
accelerator: 'Cmd+,',
click: () => {
redir('/preferences'); // this does NOT work
},
}
...
],
});
...
};
return template;
}
// Set the menu
module.exports = function initMenu() {
const menu = Menu.buildFromTemplate(getMenuTemplate());
Menu.setApplicationMenu(menu);
};
我的文件结构很简单——三个文件都在同一个目录中。
也欢迎任何代码批评;我花了好几个小时努力想弄清楚这一切。
【问题讨论】:
标签: javascript node.js electron node-modules