question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Gatsby build fails with "Cannot read property 'toLowerCase' of undefined" message

See original GitHub issue

Description

Gatsby build fails with the message:

ERROR #98123  WEBPACK
Generating JavaScript bundles failed
Cannot read property 'toLowerCase' of undefined

The gatsby develop command shows no error. I went through a process of debugging and elimination and checked every instance of toLowerCase function use. The error message is cryptic because it doesn’t say where exactly this error happens. I used the debugger in VS Studio and the error occurs after gatsby-node.js and the breakpoints that I have setup there are processed.

Steps to reproduce

gatsby build

Expected result

gatsby build should compile

Actual result

gatsby build fails

Environment

System:
    OS: Linux 5.3 Linux Mint 19.3 (Tricia)
    CPU: (8) x64 AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx
    Shell: 4.4.20 - /bin/bash
  Binaries:
    Node: 12.13.1 - ~/.nvm/versions/node/v12.13.1/bin/node
    Yarn: 1.22.5 - ~/.yarn/bin/yarn
    npm: 6.12.1 - ~/.nvm/versions/node/v12.13.1/bin/npm
  Languages:
    Python: 2.7.17 - /usr/bin/python
  Browsers:
    Chrome: 81.0.4044.138
    Firefox: 76.0
  npmPackages:
    gatsby: ^2.24.91 => 2.25.4
    gatsby-plugin-mailchimp: ^5.2.2 => 5.2.2
    gatsby-source-contentful: ^3.1.3 => 3.1.3
  npmGlobalPackages:
    gatsby-cli: 2.11.7

Package.json

"@contentful/rich-text-react-renderer": "^14.1.2",
    "gatsby": "^2.24.91",
    "gatsby-plugin-mailchimp": "^5.2.2",
    "gatsby-source-contentful": "^3.1.3",
    "gsap": "^3.5.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-helmet": "^6.1.0",
    "react-icons": "^3.11.0",
    "react-share": "^4.3.1"

NPM debug log

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/home/stefan/.nvm/versions/node/v12.13.1/bin/node',
1 verbose cli   '/home/stefan/.nvm/versions/node/v12.13.1/bin/npm',
1 verbose cli   'run',
1 verbose cli   'build'
1 verbose cli ]
2 info using npm@6.12.1
3 info using node@v12.13.1
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: /home/stefan/.nvm/versions/node/v12.13.1/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/stefan/Coding/levels/node_modules/.bin:/home/stefan/.yarn/bin:/home/stefan/.config/yarn/global/node_modules/.bin:/home/stefan/.nvm/versions/node/v12.13.1/bin:/home/stefan/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/stefan/Dependencies/jdk1.8.0_202/bin:/home/stefan/stefan/Dependencies/Android/emulator:/home/stefan/stefan/Dependencies/Android/tools:/home/stefan/stefan/Dependencies/Android/tools/bin:/home/stefan/stefan/Dependencies/Android/platform-tools
9 verbose lifecycle gatsby-starter-hello-world@0.1.0~build: CWD: /home/stefan/Coding/levels
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> (/home/stefan/.nvm/versions/node/v12.13.1/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:210:5)
13 verbose stack     at ChildProcess.<anonymous> (/home/stefan/.nvm/versions/node/v12.13.1/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:210:5)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid gatsby-starter-hello-world@0.1.0
15 verbose cwd /home/stefan/Coding/levels
16 verbose Linux 5.3.0-51-generic
17 verbose argv "/home/stefan/.nvm/versions/node/v12.13.1/bin/node" "/home/stefan/.nvm/versions/node/v12.13.1/bin/npm" "run" "build"
18 verbose node v12.13.1
19 verbose npm  v6.12.1
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 ]

gatsby-node.js

const path = require("path")

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions 

  const categories = await graphql(`
    query MyQueryCategories {
      allContentfulBlogPost {
        edges {
          node {
            category 
          }
        }
      }
    }
`)

  const response = await graphql(`
    query MyQuery {
    allContentfulBlogPost {
      edges {
        node {
          title
          subtitle
          authorAvatar {
            file {
              url
            }
          }
          authorName
          category
          content {
            json
          }
          featuredImage {
            file {
              url
            }
          }
          date(formatString: "MMMM DD, YYYY")
        }
      }
    }
  }
`)

  let allCategories = []
  let categoriesUniq = []

  categories.data.allContentfulBlogPost.edges.forEach(x => 
    allCategories.push(x.node.category)
  )

  categoriesUniq = Array.from( new Set(allCategories))   

  response.data.allContentfulBlogPost.edges.forEach(article => {
    createPage({
      path: `/blog/${article.node.title.replace(/ /g, "-").toLowerCase()}`,
      component: path.resolve("./src/templates/blogpost.js"),
      context: {
        article: article, 
        categories: categoriesUniq
      },
    })
  })

  categoriesUniq.forEach(category => {
    createPage({
        path: `/blog-category/${category.replace(/ /g, "-").toLowerCase()}`,
        component: path.resolve("./src/templates/blogcategory.js"),
        context: {
          articles:  response.data.allContentfulBlogPost.edges.filter(article => article.node.category.toLowerCase() == category.toLowerCase()),
          category: category,
          categories: categoriesUniq
        },
    })
  })

  createPage({
        path: `/blog/`,
        component: path.resolve("./src/templates/blog.js"),
        context: {
          articles:  response.data.allContentfulBlogPost.edges,
          categories: categoriesUniq
        },
    })
}

gatsby-ssr.js

import React from "react"
export const onRenderBody = (
  { setHeadComponents, setPostBodyComponents },
  pluginOptions
) => {

  setPostBodyComponents([
    <script
      key="javascript_code"
      dangerouslySetInnerHTML={{
        __html: `
      const screenIsMobile = 720 < window.innerWidth 
        ? false
        : true;
      const _frontpageHero = document.getElementById('frontpage-hero');

          if(screenIsMobile && _frontpageHero.hasAttribute('data-hero-mobile-image')) {
          let _frontpageHeroImg = _frontpageHero.getElementsByTagName('img');

          _frontpageHeroImg[0].setAttribute('src', _frontpageHero.getAttribute('data-hero-mobile-image'))
          _frontpageHeroImg[0].setAttribute('srcset', '');
        }
      `,
      }}
    />,

    <script
      data-noptimize="1"
      key="javascript_code2"
      dangerouslySetInnerHTML={{
        __html: `
        window.lazySizesConfig=window.lazySizesConfig||{};window.lazySizesConfig.loadMode=1;
      `,
      }}
    />,   
  ])
}

gatsby-browser.js

import './src/css/home_inline.css'
import './src/css/footer_inline.css'
import './src/css/autoptimize.css'
import './src/css/general_inline.css'
import './src/css/blog_inline.css'
import './src/css/other.css'

gatsby-config.js

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

const contentfulConfig = {
  spaceId: process.env.CONTENTFUL_SPACE_ID ? process.env.CONTENTFUL_SPACE_ID : "id-here",
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN ? process.env.CONTENTFUL_ACCESS_TOKEN : "token-here",
}

if (process.env.CONTENTFUL_HOST) {
  contentfulConfig.host = process.env.CONTENTFUL_HOST
}

const { spaceId, accessToken } = contentfulConfig

if (!spaceId || !accessToken) {
  throw new Error(
    'Contentful spaceId and the access token need to be provided.'
  )
}

module.exports = {
  plugins: [
  	{
  	  resolve: 'gatsby-source-contentful',
  	  options: contentfulConfig,
  	  forceFullSync: true,
	   },
    {
      resolve: 'gatsby-plugin-mailchimp',
      options: {
          endpoint: 'endpoint-here',
          timeout: 3500, 
      },
    },
  ],
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
stefantulcommented, Nov 12, 2020

So the problem was a missing value in a css file that caused the postcss-merge-longhand package to break.

.content .wp-caption-text { margin: ; font-size: 12px; line-height: 1.25 }

Thank you very much Michal, this solves the problem!

1reaction
piehcommented, Nov 12, 2020

@stefantul I opened issue with some detail in your repository with pointer why this happens.

In terms of hiding stack trace - I hope to use your site to fix the problem of not printing relevant stack trace (one that I pasted above), but even that would likely still be pretty hard to pinpoint to exact source (I had to do few hoops and put debugging breakpoints inside postcss-merge-longhand to find where it comes from)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot read property 'toLowerCase' of Undefined in JS
The "Cannot read property 'toLowerCase' of undefined" error occurs when calling the toLowerCase() method on an undefined value. To solve the error, ...
Read more >
Cannot read property 'toLowerCase' of undefined CompileError
I have a project which works fine when I run npm start but fails with this error when I run npm run build...
Read more >
npm run build - Failed to compile - Cannot read property ...
Coding example for the question npm run build - Failed to compile - Cannot read property 'toLowerCase' of undefined-Reactjs.
Read more >
cannot read properties of undefined (reading 'search') - You.com ...
You are getting that response in your console because you are trying to access a property from an object that does not exist...
Read more >
Michael Uloth — How ecobee Uses Slack to Report Data Entry ...
My team at ecobee spent months debugging build failures on the staging site for ... Cannot read property X of null or Cannot...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found