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

WebpackError with no indication of where it happens (stacktrace) #25507

Closed
lionzan opened this issue Jul 3, 2020 · 12 comments
Closed

WebpackError with no indication of where it happens (stacktrace) #25507

lionzan opened this issue Jul 3, 2020 · 12 comments
Assignees
Labels
status: needs reproduction This issue needs a simplified reproduction of the bug for further troubleshooting. topic: cli Related to the Gatsby CLI type: bug An issue or pull request relating to a bug in Gatsby

Comments

@lionzan
Copy link

lionzan commented Jul 3, 2020

Summary

I get WebpackError: ReferenceError: document is not defined when trying to npm run build on a Gatsby site that works fine in develop.

But there's no indication as to where it happens.

I looked at many other similar cases online, but they all show where the code is failing. Here, nothing. I also checked the files one by one, there isn't any document in any of the js files in / or in /src/. I'm lost!

Relevant information

...
success run page queries - 0.174s - 15/15 86.30/s
failed Building static HTML for pages - 19.613s

 ERROR #95312 

"document" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html





  WebpackError: ReferenceError: document is not defined
  
  - build-html.js:107 doBuildPages
    [gatsby-auth]/[gatsby]/dist/commands/build-html.js:107:24
  
  - build-html.js:121 async buildHTML
    [gatsby-auth]/[gatsby]/dist/commands/build-html.js:121:3
  
  - build.js:206 async build
    [gatsby-auth]/[gatsby]/dist/commands/build.js:206:5
  

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! gatsby-starter-hello-world@0.1.0 build: `gatsby build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the gatsby-starter-hello-world@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/xxxxxxx/.npm/_logs/2020-07-03T15_58_09_580Z-debug.log

and here is the log file content

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/leonardo13/.nvm/versions/node/v14.2.0/bin/node',
1 verbose cli   '/Users/leonardo13/.nvm/versions/node/v14.2.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'build'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v14.2.0
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle gatsby-starter-hello-world@0.1.0~prebuild: gatsby-starter-hello-world@0.1.0
6 info lifecycle gatsby-starter-hello-world@0.1.0~build: gatsby-starter-hello-world@0.1.0
7 verbose lifecycle gatsby-starter-hello-world@0.1.0~build: unsafe-perm in lifecycle true
8 verbose lifecycle gatsby-starter-hello-world@0.1.0~build: PATH: /Users/leonardo13/.nvm/versions/node/v14.2.0/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/leonardo13/Gatsby/gatsby-auth/node_modules/.bin:/Users/leonardo13/.nvm/versions/node/v14.2.0/bin:~/System:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
9 verbose lifecycle gatsby-starter-hello-world@0.1.0~build: CWD: /Users/leonardo13/Gatsby/gatsby-auth
10 silly lifecycle gatsby-starter-hello-world@0.1.0~build: Args: [ '-c', 'gatsby build' ]
11 silly lifecycle gatsby-starter-hello-world@0.1.0~build: Returned: code: 1  signal: null
12 info lifecycle gatsby-starter-hello-world@0.1.0~build: Failed to exec build script
13 verbose stack Error: gatsby-starter-hello-world@0.1.0 build: `gatsby build`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/Users/leonardo13/.nvm/versions/node/v14.2.0/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:315:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/leonardo13/.nvm/versions/node/v14.2.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:315:20)
13 verbose stack     at maybeClose (internal/child_process.js:1051:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)
14 verbose pkgid gatsby-starter-hello-world@0.1.0
15 verbose cwd /Users/leonardo13/Gatsby/gatsby-auth
16 verbose Darwin 19.4.0
17 verbose argv "/Users/leonardo13/.nvm/versions/node/v14.2.0/bin/node" "/Users/leonardo13/.nvm/versions/node/v14.2.0/bin/npm" "run" "build"
18 verbose node v14.2.0
19 verbose npm  v6.14.4
20 error code ELIFECYCLE
21 error errno 1
22 error gatsby-starter-hello-world@0.1.0 build: `gatsby build`
22 error Exit status 1
23 error Failed at the gatsby-starter-hello-world@0.1.0 build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Environment (if relevant)

File contents (if changed)

gatsby-config.js:

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})


module.exports = {
  siteMetadata: {
...
  },
  plugins: [
    {
      resolve: "gatsby-source-google-spreadsheet",
      options: {
        spreadsheetId: "xyzxyz",
        spreadsheetName: "MySheet",
        typePrefix: "GoogleSpreadsheet",
        credentials: require('./xyzxyz.json'),
        filterNode: () => true,
        mapNode: node => node
      }
    },
    {
      resolve: `gatsby-plugin-prefetch-google-fonts`,
      options: {
        fonts: [
          {
            family: `Roboto`,
            variants: [`300`,`400`,`700`,`700i`],
          },
          {
            family: `Krona One`,
            variants: [`400`],
          },
        ],
      },
    },
    {
        resolve: `gatsby-source-filesystem`,
        options: {
            name: `markdown-pages`,
            path: `${__dirname}/src/mdpages`,
        },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `startupsimage`,
        path: `${__dirname}/src/images/startups/image/`,
      },
    },
    `gatsby-transformer-remark`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images/`,
      },
    },
    `gatsby-plugin-modal-routing`,
  ],
}

package.json: N/A

gatsby-node.js:

// Implement the Gatsby API “onCreatePage”. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*"

    // Update the page.
    createPage(page)
  }
}
exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions

// Blog posts

  const blogPostTemplate = require.resolve(`./src/templates/blog.js`)

  const result = await graphql(`
    {
      allMarkdownRemark(
        sort: { order: DESC, fields: [frontmatter___date] }
        limit: 1000
      ) {
        edges {
          node {
            frontmatter {
              slug
            }
          }
        }
      }
    }
  `)

  // Handle errors
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.frontmatter.slug,
      component: blogPostTemplate,
      context: {
        // additional data can be passed via context
        slug: node.frontmatter.slug,
      },
    })
  })


// Startups

  const returnedstartups = await graphql(`
    query MyQuery {
      allGoogleSpreadsheetMySheetStartups {
        edges {
          previous {
            coId
            coTitle
          }
          next {
            coId
            coTitle
          }
          node {
            coId
            coDate
            coTitle
            coLogo
            coImage
            coWebsite
            coLinkedin
            coTwitter
            coYrFounded
            coLocation
            coNatSol
            coMaritime
            coDigital
            coPhysical
            coOneLiner
            co100Words
            coTechnologies
            coApplications
            coCategories
            coSection
            coAchievements
            coPress
            coInterview
            coIntDate
            coIntNotes
            coLevel
            coVisibility
            coWeight
          }
        }
      }
    }
    `
  )

  if (returnedstartups.errors) {
    throw returnedstartups.errors
  }

  const startups = returnedstartups.data.allGoogleSpreadsheetMySheetStartups.edges

  startups.forEach((startup, index) => {
    console.log(`${startup.node.coId} created`);
    createPage({
      path: `/startups/${startup.node.coId}`,
      component: require.resolve("./src/components/startupPage.js"),
      context: {
        ID : startup.node.coId,
        data: startup.node,
        prev: startup.previous,
        next: startup.next,
        image: `../images/startups/logo/${startup.node.coId}.png`
      },
    })
  })
  createPage({
      path: `/startups`,
      component: require.resolve("./src/templates/startupsList.js"),
      context: {
        data: startups,
      },
    })
}

gatsby-browser.js: N/A
gatsby-ssr.js: N/A

@lionzan lionzan added the type: question or discussion Issue discussing or asking a question about Gatsby label Jul 3, 2020
@gatsbot gatsbot bot added type: documentation An issue or pull request for improving or updating Gatsby's documentation status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer labels Jul 3, 2020
@lionzan lionzan changed the title WebpackError: ReferenceError: document is not defined Again, with no indication of where it happens. WebpackError: ReferenceError: document is not defined with no indication of where it happens. Jul 3, 2020
@lionzan lionzan changed the title WebpackError: ReferenceError: document is not defined with no indication of where it happens. "WebpackError: ReferenceError: document is not defined" in build, with no indication of where it happens. Jul 3, 2020
@3scava1i3r
Copy link
Contributor

To fix this, find the offending code and either

1)check before calling the code if window is defined so the code doesn’t run while Gatsby is building (see code sample below) or
2)if the code is in the render function of a React.js component, move that code into componentDidMount which ensures the code doesn’t run unless it’s in the browser.

and you can visit:https://www.gatsbyjs.org/docs/debugging-html-builds/ for more info

@lionzan
Copy link
Author

lionzan commented Jul 6, 2020

Hi @escavalier thank you.

find the offending code

As you can see from my post there is no indication where my code fails. Moreover there is no reference to document anywhere in my code.

The error message mentions a build.js and a build-hrml.js files but I guess they are build files, not under my control.

And of course I checked https://www.gatsbyjs.org/docs/debugging-html-builds/
but to no avail.

Any other suggestion?

@pieh
Copy link
Contributor

pieh commented Jul 6, 2020

We fixed error message (particularly stack trace and location) in #25385 which was released in gatsby@2.23.12. So I would suggest upgrading gatsby (I assume you have bit older version here, because I don't see any gatsby version specified in issue) which should then give you actual location of a problem (this very well may be in 3rd party components that are NOT SSR friendly)

@pieh pieh added topic: cli Related to the Gatsby CLI topic: SSG* and removed status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer type: documentation An issue or pull request for improving or updating Gatsby's documentation labels Jul 6, 2020
@pieh pieh self-assigned this Jul 6, 2020
@lionzan
Copy link
Author

lionzan commented Jul 6, 2020

Hi @pieh actually yes I have a slightly older version:

$ gatsby --version
Gatsby CLI version: 2.12.21
Gatsby version: 2.23.3

Updating now and I will post about results.
Thanks!

@lionzan
Copy link
Author

lionzan commented Jul 6, 2020

@pieh , changed to

gatsby --version
Gatsby CLI version: 2.12.21
Gatsby version: 2.23.21

But now i get new errors that i don't know how to handle, such as

Error: Cannot use GraphQLInputObjectType "FileInput" from another module or realm.

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.

But I didn't change anything :/

Help!

@LekoArts LekoArts added status: needs reproduction This issue needs a simplified reproduction of the bug for further troubleshooting. and removed type: question or discussion Issue discussing or asking a question about Gatsby labels Jul 8, 2020
@LekoArts LekoArts changed the title "WebpackError: ReferenceError: document is not defined" in build, with no indication of where it happens. WebpackError with no indication of where it happens (stacktrace) Jul 8, 2020
@LekoArts
Copy link
Contributor

LekoArts commented Jul 8, 2020

Please create a minimal reproduction. This is a simplified example of the issue that makes it clear and obvious what the issue is and how we can begin to debug it.

@LekoArts LekoArts added the type: bug An issue or pull request relating to a bug in Gatsby label Jul 8, 2020
@Jacob124
Copy link

Jacob124 commented Jul 8, 2020

I guess the main "Bug" is the lack of information being given after the error. Just so that we're on the same page, is this not a normal thing? I mean, does the build usually fail with a better explanation as to why?

@Jacob124
Copy link

Jacob124 commented Jul 8, 2020

I figured out my issue:
I was using gatsby's navigate function before a component was mounted. Navigate uses the window object under the hood. It makes sense I wasn't able to find it using by searching my node_modules folder since it's installed globally.
I found it by trying to make a minimal reproduction. When I added the pages that had 'navigate' the build failed, but this time, it showed me exactly what was causing the error! I still don't know why my real project isn't outputting verbose errors.

@freiksenet
Copy link
Contributor

Hi @Jacob124!

I'm glad that you managed to find the error! However, as we can't do much to help about the errors not being show without a reproduction, I'll have to close this issue :( If you are able to create a minimal reproduction for this then please do reopen the issue. If you want to share your real project, you can also send it to me directly to freiksenet@gatsbyjs.com and then we can debug it further.

Thanks!

@brootle
Copy link

brootle commented Jul 21, 2020

FIXED... see all to the end

OK, so now I also run into same problem and looks like will have to rebuild the project from point zero step by step to trace what is causing this problem as there is no indication where it comes from ;) My Gatsby version is 2.22.15

failed Building static HTML for pages - 6.883s

ERROR #95312

"document" is not available during server side rendering.

See our docs page for more info on this error: https://gatsby.dev/debug-html

WebpackError: ReferenceError: document is not defined

  • build-html.js:110 doBuildPages
    [docs]/[gatsby]/dist/commands/build-html.js:110:24

  • build-html.js:124 async buildHTML
    [docs]/[gatsby]/dist/commands/build-html.js:124:3

  • build.js:200 async build
    [docs]/[gatsby]/dist/commands/build.js:200:5

UPDATE

After updating Gatsby to 2.24.7 I now can see what is causing the error and that is
<SEO title={mdx.frontmatter.post_title} description={document.excerpt} />

That is funny, because initially I did have variable name document that had data from graphql query, but changed it to mdx after adding mdx, and forgot to rename variable, at the same time Gatsby didn't raise any error during develop as Gatsby interpreted document as global variable related to html page, and only during build process after updating to latest version it noticed that something was not correct here :)

@LekoArts
Copy link
Contributor

LekoArts commented Jul 21, 2020

Please use a version equal to or later than 2.23.12 as pointed out here: #25507 (comment)

@brootle
Copy link

brootle commented Jul 21, 2020

@LekoArts Thanks, I got it fixed, but it's a kind of funny how I did build a ground for this problem initially

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: needs reproduction This issue needs a simplified reproduction of the bug for further troubleshooting. topic: cli Related to the Gatsby CLI type: bug An issue or pull request relating to a bug in Gatsby
Projects
None yet
Development

No branches or pull requests

7 participants