【问题标题】:TypeError: x is not a function in Node.jsTypeError:x 不是 Node.js 中的函数
【发布时间】:2018-11-26 13:37:24
【问题描述】:

我正在开发一个 Electron 应用程序,我的目标是“拆分”index.js(主进程)文件。目前,我已将与菜单栏相关和与触控栏相关的代码放入两个单独的文件中,menu.jstouchBar.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


    【解决方案1】:

    redir 它不是一个函数,因为您正在导出一个对象,其中包含一个 redir 属性,它是一个函数。

    所以你应该使用:

    const { redir } = require('./index.js');
    

    或者这样导出

    module.exports = redir
    

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

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

    【讨论】:

      【解决方案2】:

      您正在导出

      module.exports.redir = redir;
      

      这意味着你的导入

      const redir = require('./index');
      

      是导出的对象。 redir 恰好是它的关键之一。要使用该功能,请使用

      const redir = require('./index').redir;
      

      或者直接解构成redir

      const { redir } = require('./index');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        • 2018-01-09
        • 1970-01-01
        • 2019-08-25
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多