Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React-GA (Google Analytics) throwing errors on build #412

Closed
urcades opened this issue Sep 1, 2016 · 3 comments
Closed

React-GA (Google Analytics) throwing errors on build #412

urcades opened this issue Sep 1, 2016 · 3 comments

Comments

@urcades
Copy link

urcades commented Sep 1, 2016

Hello! Right now I'm being thrown the following errors after installing the React-GA npm module:

gatsby build
Generating CSS
Generating Static HTML
Failed at generating HTML

/Users/edouard/Projects/ed/projects/edouard-us/node_modules/gatsby/dist/bin/cli.js:39
      throw err;
      ^
Error: ReferenceError: window is not defined
    at Object.ReactGA.initialize (render-page.js:49431:9)
    at Object.<anonymous> (render-page.js:48904:20)
    at __webpack_require__ (render-page.js:30:30)
    at webpackContext (render-page.js:48741:10)
    at render-page.js:25077:18
    at Array.forEach (native)
    at module.exports (render-page.js:25070:10)
    at render-page.js:89:40
    at module.exports (render-page.js:48644:11)
    at Object.<anonymous> (render-page.js:88:2)

This is after installing the module via npm and importing it into my root index.js file as so:

import React from 'react'
import { Link } from 'react-router'
... etc.
... etc. 
import ReactGA from 'react-ga';
ReactGA.initialize('UA-XXXXXXX-1');

exports.onRouteUpdate = (state, page, pages) => {
  ReactGA.pageview(state.pathname);
};

Do you happen to have any direct idea as to why this would throw errors on build? While in develop mode everything appears to work fine, and while viewing source, I definitely see the intact GA script included at the end of the page.

Thanks!

@KyleAMathews
Copy link
Contributor

When Gatsby builds a site it's not running in a browser so the window object is not available. So if a React component relies on window it can't be rendered on the server.

The easiest work-around is to require the component in componentDidMount as that code will only be run in the browser.

@urcades
Copy link
Author

urcades commented Sep 2, 2016

Hello again!

While trying out the method you brought up on twitter, which worked perfectly during development, I appeared to run into some sort of issue with the formatting of the block that delineates the GA script:

Here's how I've gone about implementing it (note this is an html.js file, not a html.cjsx in your file I was referencing)

import React from 'react'
import DocumentTitle from 'react-document-title'
import { prefixLink } from 'gatsby-helpers'
import { TypographyStyle } from 'utils/typography'

const BUILD_TIME = new Date().getTime()

module.exports = React.createClass({
  displayName: 'HTML',
  propTypes: {
    body: React.PropTypes.string,
  },
  render () {
    const { body } = this.props
    const title = DocumentTitle.rewind()

    let css
    if (process.env.NODE_ENV === 'production') {
      css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />
    }

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0 maximum-scale=5.0"
          />
          <title>{title}</title>
          <TypographyStyle />
          {css}
        </head>
        <body className="landing-page">
          <div id="react-mount" dangerouslySetInnerHTML={{ __html: body }} />
          <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
          {scripts}
          <script dangerouslySetInnerHTML={{__html: """
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

            ga('create', 'UA-59560755-1', 'auto');
            ga('send', 'pageview');
          """}}
        />
        </body>
      </html>
    )
  },
})

This file caused the issue seen here, while I attempted to build the site:

gatsby build
Generating CSS
Generating Static HTML
Failed at generating HTML

/Users/edouard/Projects/ed/projects/edouard-us/node_modules/gatsby/dist/bin/cli.js:39
      throw err;
      ^
Error: ./html.js
Module build failed: SyntaxError: /Users/edouard/Projects/ed/projects/edouard-us/html.js: Unterminated string constant (39:54)
  37 |           <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
  38 |           {scripts}
> 39 |           <script dangerouslySetInnerHTML={{__html: """
     |                                                       ^
  40 |             (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  41 |             (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  42 |             m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

It's looking like the """ which are supposed to delineate the script doesn't seem to be recognized at all. For kicks, I tried renaming the file html.cjsx to see if that was the issue, but I received an error that seems to imply the very base formatting isn't coffeescript-kosher:

gatsby build
Generating CSS
Generating Static HTML
Failed at generating HTML

/Users/edouard/Projects/ed/projects/edouard-us/node_modules/gatsby/dist/bin/cli.js:39
      throw err;
      ^
Error: ./html.cjsx
Module build failed: Error: /Users/edouard/Projects/ed/projects/edouard-us/node_modules/cjsx-loader/index.js!/Users/edouard/Projects/ed/projects/edouard-us/html.cjsx:1:1: error: reserved word 'import'
import React from 'react'
^^^^^^
    L0: import React from 'react'
         ^

@KyleAMathews
Copy link
Contributor

Ooo yeah. That's a diff between coffeescript and JavaScript. For multi line
strings coffeescript uses """ where JS uses back ticks.
On Fri, Sep 2, 2016 at 4:09 AM édouard u. [email protected] wrote:

Hello again!

While trying out the method you brought up on twitter, which worked
perfectly during development, I appeared to run into some sort of issue
with the formatting of the block that delineates the GA script:

Here's how I've gone about implementing it (note this is an html.js file,
not a html.cjsx in your file I was referencing)

import React from 'react'import DocumentTitle from 'react-document-title'import { prefixLink } from 'gatsby-helpers'import { TypographyStyle } from 'utils/typography'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({ displayName: 'HTML', propTypes: { body: React.PropTypes.string,
}, render () { const { body } = this.props const title = DocumentTitle.rewind()
let css if (process.env.NODE_ENV === 'production') { css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />
}
return (





<title>{title}</title>

{css}


<div id="react-mount" dangerouslySetInnerHTML={{ __html: body }} />
<script src={prefixLink(/bundle.js?t=${BUILD_TIME})} />
{scripts}
<script dangerouslySetInnerHTML={{__html: """ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-59560755-1', 'auto'); ga('send', 'pageview'); """}}
/>


)
},
})

This file caused the issue seen here, while I attempted to build the site:

gatsby build
Generating CSS
Generating Static HTML
Failed at generating HTML

/Users/edouard/Projects/ed/projects/edouard-us/node_modules/gatsby/dist/bin/cli.

js:39
throw err;
^
Error: ./html.js
Module build failed: SyntaxError: /Users/edouard/Projects/ed/projects/edouard-us/html.js: Unterminated string constant (39:54)
37 | <script src={prefixLink(/bundle.js?t=${BUILD_TIME})} />
38 | {scripts}

39 | <script dangerouslySetInnerHTML={{__html: """
| ^
40 | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
41 | (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
42 | m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

It's looking like the """ which are supposed to delineate the script
doesn't seem to be recognized at all. For kicks, I tried renaming the file
html.cjsx to see if that was the issue, but I received an error that
seems to imply the very base formatting isn't coffeescript-kosher:

gatsby build
Generating CSS
Generating Static HTML
Failed at generating HTML

/Users/edouard/Projects/ed/projects/edouard-us/node_modules/gatsby/dist/bin/cli.

js:39
throw err;
^
Error: ./html.cjsx
Module build failed: Error: /Users/edouard/Projects/ed/projects/edouard-us/node_modules/cjsx-loader/index.js!/Users/edouard/Projects/ed/projects/edouard-us/html.cjsx:1:1: error: reserved word 'import'
import React from 'react'
^^^^^^
L0: import React from 'react'
^


You are receiving this because you modified the open/close state.

Reply to this email directly, view it on GitHub
#412 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAEVh21DQ-kgq3bhR8gOU6Cw3kgdJ4Jlks5qmAOhgaJpZM4JzGDS
.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants