[英]TypeError: x is not a function in Node.js
我正在開發一個Electron應用程序,目的是“拆分” index.js
(主進程)文件。 目前,我已經將與菜單欄相關的代碼和與觸摸欄相關的代碼放入了兩個單獨的文件menu.js
和touchBar.js
。 這兩個文件都依賴於名為redir
的函數,該函數位於index.js
。 每當我嘗試激活菜單欄中的click
事件(依賴於redir
,都會出現錯誤:
TypeError: redir is not a function
。 這也適用於我的觸摸條形碼。
這是我的(被截斷的)文件:
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);
};
我的文件結構很簡單-所有三個文件都在同一目錄中。
也歡迎任何對代碼的批評; 我花了好幾個小時才想盡辦法解決這個問題。
redir
不是函數,因為要導出的對象包含redir
屬性,該對象是函數。
因此,您應該使用:
const { redir } = require('./index.js');
或以這種方式導出
module.exports = redir
當您執行以下操作時: module.exports.redir = redir;
您正在導出: { redir: [Function] }
您正在出口
module.exports.redir = redir;
這意味着您的導入
const redir = require('./index');
是導出的對象。 redir
恰好是其關鍵之一。 要使用該功能,請使用
const redir = require('./index').redir;
或直接分解為redir
const { redir } = require('./index');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.