gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.24k stars 10.32k forks source link

ERROR #95313 Building static HTML failed for path "/404/" #18241

Closed mbappai closed 4 years ago

mbappai commented 4 years ago

Summary

I recently implemented localization in my gatsby project using the react-intl package. I was able to pull that off by mimicking the implementation of the package in the gatsby-starter-default-contentful-i18n repo. Everything works fine when I run gatsby-develop but sadly not the same after running build.

Relevant information

The react-intl packages require some route configurations to get it up and running, which made me make use of the location props in my layout component which is exposed to the route paths which I also implemented using the earlier linked repo as a guide. However, I always meet this error.

const url = location.pathname;
     |                            ^
36 |       const { langs, defaultLangKey } = data.site.siteMetadata.languages;
37 |       const langKey = getCurrentLangKey(langs, defaultLangKey, url);
38 |       const homeLink = `/${langKey}/`;

-WebpackError: TypeError: Cannot read property 'pathname' of undefined.

I keep getting pointed towards the url variable. I made sure to cross-check all the location props that were passed down from layout component parents to make sure none of them were undefined, but still no dice. I really don't know where to start debugging this problem. Below is my index.js file.

import React from 'react';
import { graphql, navigate, withPrefix } from 'gatsby';
import { getUserLangKey } from 'ptz-i18n';

class RedirectIndex extends React.PureComponent {
  constructor(args) {
    super(args);

    // Skip build, Browsers only
    if (typeof window !== 'undefined') {
      const { langs, defaultLangKey } = args.data.site.siteMetadata.languages;
      const langKey = getUserLangKey(langs, defaultLangKey);
      const homeUrl = withPrefix(`/${langKey}/`);

      navigate(homeUrl);
    }
  }

  render() {
    // It's recommended to add your SEO solution in here for bots
    // eg. https://github.com/ahimsayogajp/ahimsayoga-gatsby/blob/master/src/pages/index.js#L22
    return (<div />);
  }
}

export default RedirectIndex;

export const pageQuery = graphql`
  query IndexQuery {
    site{
      siteMetadata{
        languages {
          defaultLangKey
          langs
        }
      }
    }
  }
`;

Environment (if relevant)

System: OS: macOS High Sierra 10.13.6 CPU: (8) x64 Intel(R) Core(TM) i7-3615QM CPU @ 2.30GHz Shell: 3.2.57 - /bin/bash Binaries: Node: 8.10.0 - /usr/local/bin/node npm: 5.6.0 - /usr/local/bin/npm Languages: Python: 2.7.15 - /usr/local/bin/python Browsers: Chrome: 77.0.3865.90 Safari: 13.0.1 npmPackages: gatsby: ^2.15.20 => 2.15.20 gatsby-image: ^2.2.20 => 2.2.20 gatsby-plugin-manifest: ^2.2.18 => 2.2.18 gatsby-plugin-netlify: ^2.1.10 => 2.1.10 gatsby-plugin-offline: ^3.0.8 => 3.0.8 gatsby-plugin-react-helmet: ^3.1.8 => 3.1.8 gatsby-plugin-sharp: ^2.2.25 => 2.2.25 gatsby-plugin-stripe: ^1.2.3 => 1.2.3 gatsby-plugin-styled-components: ^3.1.8 => 3.1.8 gatsby-source-contentful: ^2.1.42 => 2.1.42 gatsby-source-filesystem: ^2.1.26 => 2.1.26 gatsby-transformer-sharp: ^2.2.16 => 2.2.16 npmGlobalPackages: gatsby-cli: 2.5.12

File contents (if changed)

gatsby-config.js:const dotenv= require('dotenv') const languages = require('./src/data/languages');

if(process.env.NODE_ENV === 'production'){ dotenv.config() };

module.exports = { siteMetadata: { title:'A site for renting spaces for shared meetings.', description:'This site is specially designed for individuals that are interested in renting a space for having their startup meetings.', languages }, plugins: [ gatsby-plugin-react-helmet, gatsby-plugin-styled-components, { resolve: gatsby-source-filesystem, options: { name: images, path: ${__dirname}/src/images, }, }, gatsby-transformer-sharp, gatsby-plugin-sharp, // { // resolve: 'gatsby-plugin-i18n', // options: {
// langKeyDefault: 'en', // useLangKeyLayout: false // } // }, { resolve: gatsby-plugin-stripe, options: { async: true, }, }, { resolve: gatsby-plugin-manifest, options: { name: gatsby-starter-default, short_name: starter, start_url: /, background_color: #663399, theme_color: #663399, display: minimal-ui, icon: src/images/logo.PNG, // This path is relative to the root of the site. }, }, { resolve: gatsby-source-contentful, options: { spaceId: hs0zehmpjnjf, // Learn about environment variables: https://gatsby.dev/env-vars accessToken: process.env.CONTENTFUL_ACCESS_TOKEN, downloadLocal:true }, }, // gatsby-plugin-offline, ], }

package.json: N/A gatsby-node.js: const path= require('path') const fs = require("fs-extra")

// exports.onPostBuild = () => { // console.log("Copying locales") // fs.copySync( // path.join(dirname, "src/i18n/locales"), // path.join(dirname, "/public/i18n/locales") // ) // }

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

const SpacePage= path.resolve('./src/templates/spacePage/index.js')

return new Promise((resolve,reject)=>{
    graphql(`
    {
        allContentfulWorkspace{
            edges{
                node{
                    id
                    slug
                    node_locale
                  }
            }   
          }
    }
`).then(results=>{
    if(results.error){
        reject(results.error)
    }
    //create project pages

    spaces= results.data.allContentfulWorkspace.edges
    //we need a commond id specific to each item.
    //dont need the contentful id since it serves the same functionality with a slug.

    // I want to create a path with this format.
    //node_locale/slug/

    spaces.forEach(space=>{
        createPage({
            path:`/${space.node.node_locale}/${space.node.slug}`,
            component:SpacePage ,
            context:{
                slug:space.node.slug,
                id:space.node.id

            } 
        })
    })

}) .then(resolve)
}) }

gatsby-browser.js: require('typeface-ibm-plex-sans');

if (!Intl.PluralRules) { require('@formatjs/intl-pluralrules/polyfill'); require('@formatjs/intl-pluralrules/dist/locale-data/en'); // Add locale data for en require('@formatjs/intl-pluralrules/dist/locale-data/zh'); // Add locale data for zh } gatsby-ssr.js: N/A

mbappai commented 4 years ago

Never mind, I found the answer to the problem. I just happened to miss passing all the required props to the layout in all the pages that it was used. Sorry for adding to your stack of issues😇

PieterT2000 commented 4 years ago

Thanks for the hint @mujeex! I had exactly the same issue.

mbappai commented 4 years ago

I'm glad it helped you. Cheers!

lifeeric commented 4 years ago

The same error I'm getting, but I'm not providing any props and still getting the error, also tried to remove the 404 page, node_module, .cache.

lifeeric commented 4 years ago

Solved by removing React.lazy

https://stackoverflow.com/questions/62978046/building-static-html-for-pageserror-error-enoent-no-such-file-or-directory/63066839#63066839

barrymichaeldoyle commented 4 years ago

This occurred with me because I has code that bugged out in my gatsby-ssr.js file. Sorting that out solved my problem :)