hammer.js: Hammer.js fails in node since window is undefined

Hammer.js fails in node since window is undefined. Also document.

Line 2568 assumes window - https://github.com/hammerjs/hammer.js/blob/master/hammer.js#L2568

We’re trying to run a bundle produced by webpack in the web as well as node targets. It would be helpful to include the same bundle even though we’re not using hammer.js on the node side.

jQuery does something like -

typeof window !== "undefined" ? window : this

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 18
  • Comments: 26 (2 by maintainers)

Most upvoted comments

So this issue is 4 years old and still no solution? 🙄

@graingert could u possibly explain further on how to do that

Any solution now ??

After installing below 2 dependencies, I was able to launch angular universal.

  1. npm install @egjs/hammerjs --save-dev
  2. npm install @types/hammerjs --save-dev

In case anyone come here for angular ssr issue, you can use below webpack config for your server ts build.

{ test: /hammerjs/, loader: “null-loader” }

Similarly: https://medium.com/@puresmash/solve-hammer-js-issue-on-ssr-project-2e79664a7196

@egjs/hammerjs will work also, but it’s not working properly with slider on mobile in my project.

Got a fix. I downloaded the hammer.min.js.
Just wrap the if((typeof document !== 'undefined') && (typeof window !== 'undefined')){ ALL_THE_HAMMER_MIN_JS }

The reason is because Node. When youre in node it does not know what window is. You can test it in youre terminal. Here is the example:

ReferenceError: window is not defined
> if( window ) console.log( 'something' );
ReferenceError: window is not defined
> console.log( typeof window );
undefined
undefined
> if( typeof window === 'undefined' ) console.log( 'this is undefined' );
this is undefined```  

I had a similar issue with velocity-animate and (crudely) solved it via string-replace-loader

the concept is just

for the ssr entry, replace "import hammerjs from 'hammerjs'\n" with ""

and the loader config

test: /\.js$/,
loader: 'string-replace-loader',
options: {
  search: "import hammerjs from 'hammerjs'\n",
  replace: '',
}

this is working for me in my vue ssr setup currently

thank you @polymer940c , is there a way to override/polyfill hammer in a way that would not require its source code change in the node_modules? thx again for the suggestion!

Another solution is to load hammer on demand where you need it, so that you don’t have to update hammer.min.js:

if (typeof window !== undefined) { // conditional include because window is undefined on build this.hammer = await import( /* webpackPrefetch: true */ 'hammerjs' ); }