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

Created on 12 Nov 2020  路  5Comments  路  Source: gatsbyjs/gatsby

### 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 [email protected]
3 info using [email protected]
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle [email protected]~prebuild: [email protected]
6 info lifecycle [email protected]~build: [email protected]
7 verbose lifecycle [email protected]~build: unsafe-perm in lifecycle true
8 verbose lifecycle [email protected]~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 [email protected]~build: CWD: /home/stefan/Coding/levels
10 silly lifecycle [email protected]~build: Args: [ '-c', 'gatsby build' ]
11 silly lifecycle [email protected]~build: Returned: code: 1  signal: null
12 info lifecycle [email protected]~build: Failed to exec build script
13 verbose stack Error: [email protected] 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 [email protected]
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 [email protected] build: `gatsby build`
22 error Exit status 1
23 error Failed at the [email protected] 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, 
      },
    },
  ],
}
confirmed bug

All 5 comments

Hi @stefantul!

Are you able to provide reproduction site / repository so we could try to debug it too (and hopefully fix the problem of not providing more details in error message)? It could be either Minimal reproduction or your site if it's really not possible to zoom in on exact problem. If you are not conformable sharing site publicly, sending details to [email protected] could also work (if you are comfortable with that).

Otherwise we won't be able to assist much :(

Hello Michal,

I have sent you an invitation to a private git repository. Some of the things that I did: updated node, updated the packages did a gatsby clean and deleted yarn.lock and reinstalled the packages, removed all references in the code to the toLowerCase function but the error still persists, removed some of the packages and their use in the code...I'm guessing that at this point it doesn't have something to do with my code since I did the process of elimination.

Thank you for invitation. I definitely can reproduce, didn't find the root cause yet, but the stack trace is as follow:

TypeError: Cannot read property 'toLowerCase' of undefined
    at /Users/misiek/test/i27993/styles.014fa27f20ba1b7a3ca7.css:9367:1
    at hasInherit (/Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/lib/canMerge.js:16:39)
    at Array.some (<anonymous>)
    at /Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/lib/canMerge.js:21:15
    at /Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/lib/decl/boxBase.js:103:44
    at mergeRules (/Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/lib/mergeRules.js:53:17)
    at Object.merge (/Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/lib/decl/boxBase.js:102:38)
    at /Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/index.js:22:19
    at Array.forEach (<anonymous>)
    at callback (/Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/index.js:20:28)
    at callback (/Users/misiek/test/i27993/node_modules/postcss/lib/container.es6:208:18)
    at callback (/Users/misiek/test/i27993/node_modules/postcss/lib/container.es6:110:18)
    at Root.each (/Users/misiek/test/i27993/node_modules/postcss/lib/container.es6:76:16)
    at Root.walk (/Users/misiek/test/i27993/node_modules/postcss/lib/container.es6:107:17)
    at Root.walkRules (/Users/misiek/test/i27993/node_modules/postcss/lib/container.es6:206:19)
    at /Users/misiek/test/i27993/node_modules/postcss-merge-longhand/dist/index.js:19:13
    at initializePlugin (/Users/misiek/test/i27993/node_modules/cssnano/dist/index.js:31:51)

So the error originates from postcss-merge-longhand module. I didn't yet track the trigger for it (just adding updates as I go through it)

@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)

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

benstr picture benstr  路  3Comments

dustinhorton picture dustinhorton  路  3Comments

KyleAMathews picture KyleAMathews  路  3Comments

brandonmp picture brandonmp  路  3Comments

signalwerk picture signalwerk  路  3Comments