How do you publish a gatsby project with gatsby-image on Netlify?

随声附和 提交于 2021-01-02 03:47:37

问题


So I can locally build my gatsby project no problem, but when Netlify tries to build, I get the error

Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: error There was an error in your GraphQL query:
5:34:38 PM: Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: error There was an error in your GraphQL query:
5:34:38 PM: Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: failed extract queries from components - 0.439s

Which is essentially just telling me I need to build in production mode to see the full error right? Production mode is fine because that's on my local computer.

I am using gatsby-image and gatsby-background-image which i hear might cause problems? I tried adding gatsby-remark-relative-images and followed the instructions on this blog post but am still getting the same errors


I also added an environment variable for the node version which did nothing, but i read it might be useful in this "Step by Step" guide for Netlify and Gatsby


Here's the whole console log that Netlify gives me

5:33:23 PM: Build ready to start
5:33:25 PM: build-image version: 30f629161c0736b1a3ecd8b418e5eeffab5c0faf
5:33:25 PM: build-image tag: v3.3.14
5:33:25 PM: buildbot version: c59536cd5af8d84bd2f02c6af4027561b250018a
5:33:25 PM: Fetching cached dependencies
5:33:25 PM: Starting to download cache of 254.9KB
5:33:25 PM: Finished downloading cache in 71.841033ms
5:33:25 PM: Starting to extract cache
5:33:25 PM: Failed to fetch cache, continuing with build
5:33:25 PM: Starting to prepare the repo for build
5:33:25 PM: No cached dependencies found. Cloning fresh repo
5:33:25 PM: git clone https://github.com/samgermain/sudSaskV2
5:33:28 PM: Preparing Git Reference refs/heads/master
5:33:28 PM: Starting build script
5:33:28 PM: Installing dependencies
5:33:29 PM: Downloading and installing node v14.3.0...
5:33:30 PM: Downloading https://nodejs.org/dist/v14.3.0/node-v14.3.0-linux-x64.tar.xz...
5:33:30 PM: Computing checksum with sha256sum
5:33:30 PM: Checksums matched!
5:33:33 PM: Now using node v14.3.0 (npm v6.14.5)
5:33:33 PM: Started restoring cached build plugins
5:33:33 PM: Finished restoring cached build plugins
5:33:34 PM: Attempting ruby version 2.6.2, read from environment
5:33:35 PM: Using ruby version 2.6.2
5:33:35 PM: Using PHP version 5.6
5:33:35 PM: 5.2 is already installed.
5:33:35 PM: Using Swift version 5.2
5:33:35 PM: Started restoring cached node modules
5:33:35 PM: Finished restoring cached node modules
5:33:35 PM: Installing NPM modules using NPM version 6.14.5
5:34:18 PM: > sharp@0.25.3 install /opt/build/repo/node_modules/sharp
5:34:18 PM: > (node install/libvips && node install/dll-copy && prebuild-install --runtime=napi) || (node-gyp rebuild && node install/dll-copy)
5:34:19 PM: info
5:34:19 PM: sharp
5:34:19 PM:  Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.9.1/libvips-8.9.1-linux-x64.tar.gz
5:34:21 PM: > node-sass@4.14.1 install /opt/build/repo/node_modules/node-sass
5:34:21 PM: > node scripts/install.js
5:34:21 PM: Downloading binary from https://github.com/sass/node-sass/releases/download/v4.14.1/linux-x64-83_binding.node
5:34:22 PM: Download complete
5:34:22 PM: Binary saved to /opt/build/repo/node_modules/node-sass/vendor/linux-x64-83/binding.node
5:34:22 PM: Caching binary to /opt/buildhome/.npm/node-sass/4.14.1/linux-x64-83_binding.node
5:34:22 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/@babel/polyfill/node_modules/core-js
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:22 PM: Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
5:34:22 PM: The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
5:34:22 PM: > https://opencollective.com/core-js 
5:34:22 PM: > https://www.patreon.com/zloirock 
5:34:22 PM: Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
5:34:22 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/babel-polyfill/node_modules/core-js
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:22 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/babel-runtime/node_modules/core-js
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:22 PM: > core-js@3.6.5 postinstall /opt/build/repo/node_modules/core-js
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:22 PM: > core-js-pure@3.6.5 postinstall /opt/build/repo/node_modules/core-js-pure
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:23 PM: > core-js@2.6.11 postinstall /opt/build/repo/node_modules/gatsby/node_modules/core-js
5:34:23 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:24 PM: > gatsby-telemetry@1.3.9 postinstall /opt/build/repo/node_modules/gatsby-telemetry
5:34:24 PM: > node src/postinstall.js || true
5:34:24 PM: > cwebp-bin@5.1.0 postinstall /opt/build/repo/node_modules/cwebp-bin
5:34:24 PM: > node lib/install.js
5:34:25 PM:   ✔ cwebp pre-build test passed successfully
5:34:25 PM: > mozjpeg@6.0.1 postinstall /opt/build/repo/node_modules/mozjpeg
5:34:25 PM: > node lib/install.js
5:34:25 PM:   ✔ mozjpeg pre-build test passed successfully
5:34:25 PM: > pngquant-bin@5.0.2 postinstall /opt/build/repo/node_modules/pngquant-bin
5:34:25 PM: > node lib/install.js
5:34:26 PM:   ✔ pngquant pre-build test passed successfully
5:34:26 PM: > gatsby-cli@2.12.36 postinstall /opt/build/repo/node_modules/gatsby/node_modules/gatsby-cli
5:34:26 PM: > node scripts/postinstall.js
5:34:26 PM: > gatsby@2.22.11 postinstall /opt/build/repo/node_modules/gatsby
5:34:26 PM: > node scripts/postinstall.js
5:34:26 PM: > node-sass@4.14.1 postinstall /opt/build/repo/node_modules/node-sass
5:34:26 PM: > node scripts/build.js
5:34:26 PM: Binary found at /opt/build/repo/node_modules/node-sass/vendor/linux-x64-83/binding.node
5:34:26 PM: Testing binary
5:34:27 PM: Binary is fine
5:34:29 PM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/fsevents):
5:34:29 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
5:34:29 PM: npm WARN
5:34:29 PM:  optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules/chokidar/node_modules/fsevents):
5:34:29 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
5:34:29 PM: added 2392 packages from 1321 contributors and audited 2401 packages in 53.15s
5:34:32 PM: 155 packages are looking for funding
5:34:32 PM:   run `npm fund` for details
5:34:32 PM: found 0 vulnerabilities
5:34:32 PM: NPM modules installed
5:34:32 PM: Started restoring cached go cache
5:34:32 PM: Finished restoring cached go cache
5:34:32 PM: go version go1.12 linux/amd64
5:34:32 PM: go version go1.12 linux/amd64
5:34:32 PM: Installing missing commands
5:34:32 PM: Verify run directory
5:34:32 PM: Executing user command: gatsby build
5:34:35 PM: success open and validate gatsby-configs - 0.060s
5:34:36 PM: success load plugins - 1.351s
5:34:36 PM: success onPreInit - 0.015s
5:34:36 PM: success delete html and css files from previous builds - 0.025s
5:34:36 PM: success initialize cache - 0.008s
5:34:36 PM: success copy gatsby files - 0.044s
5:34:36 PM: success onPreBootstrap - 0.008s
5:34:36 PM: success createSchemaCustomization - 0.013s
5:34:37 PM: success source and transform nodes - 0.285s
5:34:37 PM: success building schema - 0.463s
5:34:37 PM: success createPages - 0.050s
5:34:37 PM: success createPagesStatefully - 0.095s
5:34:37 PM: success onPreExtractQueries - 0.000s
5:34:37 PM: success update schema - 0.031s
5:34:38 PM: error There was an error in your GraphQL query:
5:34:38 PM: Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: error There was an error in your GraphQL query:
5:34:38 PM: Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: error There was an error in your GraphQL query:
5:34:38 PM: Field "featuredImage" must not have a selection since type "String" has no subfields.
5:34:38 PM: This can happen if you e.g. accidentally added { } to the field "featuredImage". If you didn't expect "featuredImage" to be of type "String" make sure that your input source and/or plugin is correct.
5:34:38 PM: failed extract queries from components - 0.439s
5:34:38 PM: Skipping functions preparation step: no functions directory set
5:34:38 PM: Caching artifacts
5:34:38 PM: Started saving node modules
5:34:38 PM: Finished saving node modules
5:34:38 PM: Started saving build plugins
5:34:38 PM: Finished saving build plugins
5:34:38 PM: Started saving pip cache
5:34:44 PM: Finished saving pip cache
5:34:44 PM: Started saving emacs cask dependencies
5:34:44 PM: Finished saving emacs cask dependencies
5:34:44 PM: Started saving maven dependencies
5:34:44 PM: Finished saving maven dependencies
5:34:44 PM: Started saving boot dependencies
5:34:44 PM: Finished saving boot dependencies
5:34:44 PM: Started saving go dependencies
5:34:44 PM: Finished saving go dependencies
5:34:47 PM: Error running command: Build script returned non-zero exit code: 1
5:34:47 PM: Failed during stage 'building site': Build script returned non-zero exit code: 1
5:34:47 PM: Failing build: Failed to build site
5:34:50 PM: Finished processing build request in 1m25.525936502s

gatsby-node.js

const { createFilePath } = require(`gatsby-source-filesystem`)
const { fmImagesToRelative } = require('gatsby-remark-relative-images');
const path = require("path")

const replacePath = path => (path === `/` ? path : path.replace(/\/$/, ``))

exports.createPages = async ({ actions: { createPage }, graphql }) => {
  const postTemplate = path.resolve(`src/components/Article/index.tsx`)

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

  if (result.errors) {
    return Promise.reject(result.errors)
  }

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: replacePath(node.fields.slug),
      component: postTemplate,
    })
  })
}

exports.onCreateNode = ({ node, getNode, actions }) => {
  fmImagesToRelative(node)
  if (node.internal.type === `MarkdownRemark`)
    actions.createNodeField({
      node,
      name: `slug`,
      value: replacePath(createFilePath({ node, getNode, basePath: `pages` })),
    })
  
}

Markdown Template

const ShareButtons = (
  {siteUrl, shareImageUrl, title, description} : {siteUrl : string, shareImageUrl : string, title : string, description : string}
) => {
  const butCls='m-1'
  return (
    <div className='d-flex'>
      <FacebookShareButton 
        className={butCls}
        url={siteUrl}
      >
        <FontAwesomeIcon icon={faFacebook} />
      </FacebookShareButton>
      
      <TwitterShareButton 
        className={butCls}
        url={siteUrl}
        title={title}
      >
        <FontAwesomeIcon icon={faTwitter} />
      </TwitterShareButton>
      
    
    </div>
  )
}

const ArticleBanner = (
  {title, author, category, date, siteUrl, shareImageUrl, description } : 
  {title : string, author : string, category : string, date : string, siteUrl : string, shareImageUrl: string, description: string}
) => (
  <div>
    <h5>{category}</h5>
    <h1>{title}</h1>
    <small><p>{author} • {date}</p></small>
    <ShareButtons 
      {...{siteUrl, shareImageUrl, title, description}}
    />

  </div>
)

const Article = ({ data }: { data: IPostRequest }) => {
  // Helper to organize useful data in request
  const {
    markdownRemark: {
      fields:{
        slug
      },
      frontmatter: {
        featuredImage,
        // cover,
        title,
        subTitle,
        author,
        description,
        category,
        date,
      },
      html,
    },
    site: {
      siteMetadata: {
        domain
      }
    }
  } = data

  const siteUrl = `${domain}${slug}`
  const shareImageUrl = `${domain}${featuredImage.childImageSharp.fluid.src}` //ignore this error
  const metadata: ArticleMetadata = {
      author,
      description,
      title: `${title} | ${subTitle} `,
      siteUrl,
      shareImageUrl
  }

  return (
    <Layout siteMetadata={metadata} title={title}>
      <Row className='w-100'>
        <Col xs={2}></Col>
        <Col xs={8}>
          <ArticleBanner
            {...{title, author, category, date, siteUrl, shareImageUrl, description}}
          />  
          {/* <CoverImg />             */}
          <div id="article-content" dangerouslySetInnerHTML={{ __html: html }} />
        </Col>
        <Col md={3}></Col>
      </Row>
        
    </Layout>
  )
}

export default Article

export const pageQuery = graphql`
  query($path: String!) {
    allMarkdownRemark(
      limit: 4
      sort: { order: DESC, fields: [frontmatter___date] }
    ) {
      edges {
        node {
          timeToRead
          excerpt(pruneLength: 100)
          fields {
            slug
          }
          frontmatter {
            title
            date(formatString: "MMMM DD, YYYY")
          }
        }
      }
    }
    markdownRemark(fields: { slug: { eq: $path } }) {
      fields {
        slug
      }
      excerpt
      html
      frontmatter {
        title
        subTitle
        date(formatString: "MMMM DD, YYYY  hh:mm a")
        author
        category
        description
        featuredImage {
          childImageSharp {
            fluid {
              src
              srcSet
              sizes
              aspectRatio
            }
          }
        }
      }
    }
    site{
      siteMetadata{
        domain
      }
    }
    authorPicture: file(relativePath: { eq: "author.jpg" }) {
      childImageSharp {
        fixed(width: 40, height: 40) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

Just ask if you want to see any specific files


回答1:


To manage images with Netlify+Gatsby you need to install gatsby-remark-relative-images plugin. This is because you need to query images that are placed outside the directory (normally assets are placed under /assets folder).

From its documentation:

Convert image src(s) in markdown to be relative to their node’s parent directory. This will help gatsby-remark-images match images outside the node folder. For example, use with NetlifyCMS.

NOTE: This was built for use with NetlifyCMS and should be considered a temporary solution until relative paths are supported. If it works for other use cases then great!

Then, in your gatsby-node.js, you need to place the following snippet:

const { fmImagesToRelative } = require('gatsby-remark-relative-images');

exports.onCreateNode = ({ node }) => {
  fmImagesToRelative(node);
};

This takes every node returned by your gatsby-source plugins and converts any absolute paths in markdown frontmatter data into relative paths if a matching file is found.

The next step is to set it up in your gatsby-config.js. It's important to follow the structure, placing your transformer remark plugin after gatsby-source-filesystem to avoid them to override it.

 // gatsby-source-filesystem options here
 {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        // gatsby-remark-relative-images must
        // go before gatsby-remark-images
        {
          resolve: `gatsby-remark-relative-images`,
        },
        {
          resolve: `gatsby-remark-images`,
          options: {
            // It's important to specify the maxWidth (in pixels) of
            // the content container as this plugin uses this as the
            // base for generating different widths of each image.
            maxWidth: 590,
          },
        },
      ],
    },

The final step, which is not provided in your question, is to set up the paths for uploads and images in your config.yml, should look like something like this:

media_folder: static/assets/images
public_folder: /assets/images

In Gatsby, media_folder must be set under /static path to be accessible to React and its components. So, keeping in mind the media_folder path, your public_folder path must be set accordingly. From sourcing from Netlify Gatsby documentation.

Still in the root directory, add a “static” folder. Gatsby will copy everything in the static folder into the output, so we’ll want to place the Netlify CMS configuration file as static/admin/config.yml.



来源:https://stackoverflow.com/questions/60714311/how-do-you-publish-a-gatsby-project-with-gatsby-image-on-netlify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!