您如何在Netlify上发布带有gatsby-image的gatsby项目?

问题描述 投票:-1回答:1

因此,我可以在本地构建我的gatsby项目,没问题,但是当Netlify尝试构建时,出现错误

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

基本上是在告诉我我需要在生产模式下构建才能看到完整的错误,对吗?生产模式很好,因为它在我的本地计算机上。

我使用的gatsby-imagegatsby-background-image可能会引起问题?我尝试添加gatsby-remark-relative-images并关注instructions on this blog帖子,但仍收到相同的错误


我还为节点版本添加了一个没有执行任何操作的环境变量,但是我阅读了它在Netlify和Gatsby的"Step by Step" guide中可能有用

enter image description here


这是Netlify给我的整个控制台日志

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: > [email protected] 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: > [email protected] 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: > [email protected] 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: > [email protected] 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: > [email protected] 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: > [email protected] postinstall /opt/build/repo/node_modules/core-js
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:22 PM: > [email protected] postinstall /opt/build/repo/node_modules/core-js-pure
5:34:22 PM: > node -e "try{require('./postinstall')}catch(e){}"
5:34:23 PM: > [email protected] 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: > [email protected] postinstall /opt/build/repo/node_modules/gatsby-telemetry
5:34:24 PM: > node src/postinstall.js || true
5:34:24 PM: > [email protected] 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: > [email protected] 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: > [email protected] 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: > [email protected] postinstall /opt/build/repo/node_modules/gatsby/node_modules/gatsby-cli
5:34:26 PM: > node scripts/postinstall.js
5:34:26 PM: > [email protected] postinstall /opt/build/repo/node_modules/gatsby
5:34:26 PM: > node scripts/postinstall.js
5:34:26 PM: > [email protected] 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: [email protected] (node_modules/fsevents):
5:34:29 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
5:34:29 PM: npm WARN
5:34:29 PM:  optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/chokidar/node_modules/fsevents):
5:34:29 PM: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: 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模板

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
        }
      }
    }
  }
`

只需询问您是否要查看任何特定文件

reactjs graphql gatsby netlify gatsby-image
1个回答
0
投票

要使用Netlify + Gatsby管理图像,您需要安装gatsby-remark-relative-images插件。这是因为您需要查询放置在目录外部的图像(通常将资产放置在/ assets文件夹下)。

从其文档:

将Markdown中的图片src转换为相对于其节点的父级 目录。这将有助于gatsby-remark-images图像与外部图像进行匹配 节点文件夹。例如,与NetlifyCMS一起使用。

NOTE:这是与NetlifyCMS一起使用的,应该考虑 临时解决方案,直到支持相对路径。如果可行 对于其他用例,那就太好了!

然后,在gatsby-node.js中,您需要放置以下代码段:

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

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

[这将获取您的gatsby-source插件返回的每个节点,如果找到匹配的文件,则将markdown前置数据中的任何绝对路径转换为相对路径。

下一步是在您的gatsby-config.js中进行设置。遵循此结构很重要,将转换器标记插件放在gatsby-source-filesystem之后,以免它们覆盖它。

 // 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,
          },
        },
      ],
    },

您的问题中未提供的最后一步是在config.yml中设置上传和图像的路径,应如下所示:

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

在Gatsby中,必须在media_folder路径下设置/static,React及其组件才能访问。因此,请记住media_folder路径,必须相应地设置public_folder路径。从Netlify Gatsby documentation采购。

仍然在根目录中,添加一个“静态”文件夹。盖茨比将复制 静态文件夹中的所有内容都输入到输出中,因此我们要 将Netlify CMS配置文件放置为static / admin / config.yml。

© www.soinside.com 2019 - 2024. All rights reserved.