Solve Hammer.JS issue on SSR project

Server-Side-Rendering brakes your dependencies as always…

HsuCheng Tseng
1 min readDec 23, 2017

If you are trying to use Hammer.JS on your Server Side Rendering (SSR) project like the old times, you will receive an error message: ReferenceError: window is not defined. In the meanwhile, you will probably think, “Oh! It’s easy to solve. Just move all my gesture related logic after first rendering!”. Then find yourself received this heart-breaking message again. Let’s find how to resolve this annoying message.

By tracing the source code of HammerJS, you will find the way it exports.

(function(window, document, exportName, undefined) {  /* ... */})(window, document, 'Hammer');

So, the error is seen to be thrown at the very first line.

import Hammer from 'hammerjs';

Because we really don’t need any touch event during server side render process, we might need some tricks like Dynamic Import. However, it’s still in the proposal stage, therefore, it’s not ready yet. But don’t sweat it, this Webpack package, bundle-loader will do the similar thing for us.

Just put the following lines into your server-side Webpack config.

{
test: /hammerjs/,
loader: "bundle-loader",
options: {
lazy: true
}
},

Now your app will only import HammerJS when it actually calling the related functions. Putting gesture logic after componentDidMount like this.

componentDidMount() {
initGesture();
}

We even don’t need to modify any other code.

--

--