Gatsby - Uncaught TypeError - Problem z kontekstem / kompilacją

Aug 26 2020

Rozwijałem swoją aplikację w Gatsby i utknąłem. Wszystko działa dobrze z „gatsby develop”, ale kiedy uruchamiam „gatsby build”, pojawia się błąd:

"WebpackError: TypeError: Cannot destructure property 'cursorStyles' of 'Object(...)(...)' as it is undefined."

I tak, style kursorów są zdefiniowane w kontekście, więc wszystko powinno działać idealnie lub czegoś mi brakuje. Próbowałem wyczyścić pamięć podręczną, ale nadal występuje błąd, co jest bardzo dziwne, ponieważ nie miałem żadnych problemów z lokalną pracą nad tym projektem.

EDYCJA - tak, zawinąłem aplikację gatsby z dostawcą globalnym, jak widać poniżej. Po prostu nie rozumiem, dlaczego kompilacja nie działa, skoro wyraźnie mam dostęp do kontekstu ...; /

gatsby-browser.js

import React from "react"
import { GlobalProvider } from "./src/context/globalContext"

export const wrapRootElement = ({ element }) => {
  return <GlobalProvider>{element}</GlobalProvider>
}

Kontekst - wartości są definiowane w globalnej stałej dostawcy

import React, { createContext, useReducer, useContext } from "react"

//Define Context
const GlobalStateContext = createContext()
const GlobalDispatchContext = createContext()


//Reducer
const globalReducer = (state, action) => {
    switch (action.type) {
      case "TOGGLE_THEME": {
        return {
          ...state,
          currentTheme: action.theme,
        }
      }
      case "CURSOR_TYPE": {
        return {
          ...state,
          cursorType: action.cursorType,
        }
      }
      default: {
        throw new Error(`Unhandled action type: ${action.type}`)
      }
    }
  }



  export const GlobalProvider = ({ children }) => {
    const [state, dispatch] = useReducer(globalReducer, {
      currentTheme: "dark",
      cursorType: false,
      cursorStyles: ["pointer", "hovered", "locked", "white"],
    })

    return (
        <GlobalDispatchContext.Provider value={dispatch}>
          <GlobalStateContext.Provider value={state}>
            {children}
          </GlobalStateContext.Provider>
        </GlobalDispatchContext.Provider>
      )
}

//custom hooks for when we want to use our global state
export const useGlobalStateContext = () => useContext(GlobalStateContext)

export const useGlobalDispatchContext = () => useContext(GlobalDispatchContext)

Layout.js - problem występuje podczas destrukturyzacji i używania mojego niestandardowego hooka

import React, {useState} from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"

import { createGlobalStyle, ThemeProvider } from "styled-components"
import { normalize } from "styled-normalize"

import Header from './header'
import Cursor from './customCursor'
import Navigation from './navigation'

import { useGlobalStateContext, useGlobalDispatchContext } from '../context/globalContext'


const Layout = ({ children }) => {
  const { cursorStyles, currentTheme } = useGlobalStateContext()
  const dispatch = useGlobalDispatchContext()
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  const darkTheme = {
    background: '#000',
    text:'#fff',
    red: '#ea291e'
  }

  const lightTheme = {
    background: '#fff',
    text:'#000',
    red: '#ea291e'
  }

  const onCursor = cursorType => {
    cursorType = (cursorStyles.includes(cursorType) && cursorType || false)
    dispatch({ type: "CURSOR_TYPE", cursorType: cursorType})
  }

  const [toggleMenu, setToggleMenu] = useState(false)

  return(
    <ThemeProvider theme={currentTheme === "dark" ? darkTheme : lightTheme}>
    <GlobalStyle/>
    <Cursor toggleMenu={toggleMenu} />
    <Header onCursor={onCursor} toggleMenu={toggleMenu} setToggleMenu={setToggleMenu} />
    <Navigation onCursor={onCursor} toggleMenu={toggleMenu} setToggleMenu={setToggleMenu} />
    <main>{children}</main>
    {console.log(currentTheme)}
    </ThemeProvider>
  ) 
  
  
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

Odpowiedzi

1 MrVoland Aug 27 2020 at 02:26

Wreszcie rozwiązałem to! Nie wiem dlaczego, ale wydaje mi się, że to tylko Gatsby, który pracuje w tajemniczy sposób. Skopiowałem swój kod z przeglądarki gatsby-browser i umieściłem dokładnie to samo w pliku gatsby-ssr i ... zaskakująco zniknęły dziwne błędy dotyczące "obiektu niezdefiniowanego".

Niestety, ze względu na fakt, że kompilacja gatsby w tym przypadku działa podobnie do renderowania po stronie serwera next.js, musiałem naprawić mój kod w różnych miejscach - np. Właściwości okna musiały być renderowane warunkowo - ale powielanie gatsby- kod przeglądarki do gatsby-ssr naprawił problem z budową! Więc tak jak myślałem, to nie był problem z moim kodem, a raczej problem z konfiguracją Gatsby'ego.