Search code examples
reactjsgatsbydocument

WebpackError: TypeError: document.createElement is not a function in Gatsby


const _elementStyle = document.createElement('div').style;

'gatsby build' makes error 'WebpackError: TypeError: document.createElement is not a function'. How can I solve this?


Solution

  • Global objects such as window or document are available during gatsby develop because the interpreter/parser is the browser (where obviously there's a window). However, gatsby build compiles your code in the Node server, where depending on your code logic, document or window might not be available.

    You can bypass it by adding the following condition:

    if(typeof window !== "undefined"){
      // here the logic that uses window or document
    }
    

    In your case:

    if(typeof window !== "undefined"){
      const _elementStyle = document.createElement('div').style;
    }
    

    If the responsible for using the window is a third-party dependency you can follow Gatsby Failed Build - error "window" is not available during server side rendering