Search code examples
webpackgatsbywow.js

WebpackError with wow.js and Gatsby


When I try to build my gatsby project with wowjs it tell me : 'WebpackError: ReferenceError: window is not defined' or '"window" is not available during server side rendering.'

I tried a lot of thing like on this website: https://imedadel.me/fix-window-not-defined-gatsby but nothing work. If someone have face the same error it would be a pleasure to know how to get rid of it.

Thanks everyone.


Solution

  • It's a very common issue when dealing with Gatsby and some third-party modules or performing some calculations in your components.

    gatsby develop occurs in the browser-side (summarizing) where there's a window object. On the other hand, gatsby build occurs on the server-side (your machine or your deploy system) where, for obvious reasons, there's no window or other global objects.

    If you are using a window object in your component/pages, you just need to make an easy condition to check if the window object is available:

    export const YourComponent = (props) => {
    
      if (typeof window !== 'undefined'){
         console.log('window width is', window.innerWidth)
      };
    
      return <div>I've checked the type of the window to make some calculations, preventing the code-breaking in the build time in SSR</div>;
    };
    

    If the issue comes from an external module of your code (third-party dependencies), you have two options:

    • Replace the offending module in your gatsby-node.js by adding a new webpack configuration to add a null loader for that module:

      exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
        if (stage === "build-html") {
          actions.setWebpackConfig({
            module: {
                rules: [
                {
                  test: /bad-module/,
                  use: loaders.null(),
                },
               ],
            },
          })
        } 
      }
      

      Keep in mind that the rule is a regular expression that matches the folder name inside your node_modules, you'll need to change /bad-module/ for the folder name of your broken dependency (that's why you need to add it between slashes (/)). In your case, it seems that you will need to change /bad-module/ to /wowjs/ but confirm the path.

    • Use a loadable library: this will load the dynamic modules that use window in the browser-side, once the compilation/build is done, not in the SSR (Server-Side Rendering).