ccampbell/mousetrap

Mousetrap.bind is not a function when required via npm

KerriFair opened this issue · 2 comments

package.json

   "dependencies": {
      "mousetrap": "^1.6.1"
   }

main.js

var Mousetrap = require('mousetrap');

Mousetrap.bind('Q', function() { 
   console.log('Q Pressed');
});

RunKit link: https://runkit.com/embed/24nhp0l3awzu

That's because Mousetrap is designed to work in browser environment, and Mousetrap.bind only become a function after Mousetrap.init() is called, of which the implementation is here. That call fails because it cannot find document object.

However, the real question here is why would you need Mousetrap in a Node.js env in the first place? Just curious.

I was looking to use it for an Electron app I'm building as the package was recommended here https://electron.atom.io/docs/tutorial/keyboard-shortcuts/ and I couldn't get it to work. Though now I understand why. Thank you for pointing that out for me.