类型错误:x 不是 Node.js 中的函数

Lac*_*ith 0 javascript node.js node-modules electron

我正在开发一个 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);

...
Run Code Online (Sandbox Code Playgroud)

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);
};
Run Code Online (Sandbox Code Playgroud)

我的文件结构很简单——所有三个文件都在同一个目录中。

也欢迎任何代码批评;我花了好几个小时努力想弄清楚这一切。

Mar*_*nde 5

redir它不是一个函数,因为您要导出一个包含redir属性的对象,该属性是一个函数。

所以你应该使用:

const { redir } = require('./index.js');
Run Code Online (Sandbox Code Playgroud)

或者这样导出

module.exports = redir
Run Code Online (Sandbox Code Playgroud)

当你这样做时: module.exports.redir = redir;

您正在导出: { redir: [Function] }