Search code examples
ecmascript-6webpackisomorphic-javascript

Isomorphic app and browser-specific code


I am building an isomorphic app with webpack, React, ES6 and fluxible and has run in into a following issue regarding browser-specific modules import.

For example, I want to use imagesloaded in my React component. The code for this looks like this:

import React, { PropTypes, Component, findDOMNode } from "react";
import imagesLoaded from "imagesloaded";

But, obviously, it tries to do the import on the server-side first, and the code fails miserably with an error:

ReferenceError: window is not defined

The question is — what approach should I take so the code is only included for the browser-side version? I guess I am looking for something like:

if (process.env.BROWSER) {
  require("../style/components/Shop.scss");
}

Thanks!


Solution

  • You can do it in exactly same way, that you mentioned, use require

    if (process.env.BROWSER) {
       require("imagesloaded");
    }
    

    That will work. Also there is more options to do it:

    1. Provide fake instance of the library for node environment. You can use mockery, for it.

    2. Create fake instance of window. AFAIK, imagesloaded doesn't rely of browser-specific features, only utilizes window as global namespace, so you can make alias for it.

    Like this code:

    global.window = global