Добавление внешнего размещенного признака изображения в Гэтсби - PullRequest
0 голосов
/ 21 октября 2019

Ожидаемый результат

Чтобы иметь возможность просматривать избранные изображения на моей целевой странице, эти изображения будут размещены на S3.


Фактический результат

Ошибка. Просматривать избранные изображения можно только в том случае, если они являются локальными по отношению к этому каталогу публикаций.



В моем проекте Gatsby я до сих пор успешно показывала избранные изображениядля главной страницы сообщений. Следовал учебному руководству на https://codebushi.com/gatsby-featured-images/

Но проблема в том, что я хочу использовать фотографии, размещенные на S3. В моем index.md для этого поста в настоящее время работают локальные файлы и

featuredImage: "./featured-image.jpg"

Но когда я делаю что-то вроде

featuredImage: "https://bucketnameexample.s3.us-east-2.amazonaws.com/featured-image.jpg"

, я получаю ошибку

TypeError: Cannot read property 'childImageSharp' of null

Мой запрос в моем src / pages / index.js равен

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            title
            description
            featuredImage {
              childImageSharp {
                sizes(maxWidth: 630) {
                  ...GatsbyImageSharpSizes
                }
              }
            }
          }
        }
      }
    }
  }
`



РЕДАКТИРОВАТЬ 1

Получил полезную ссылку на https://www.gatsbyjs.org/packages/gatsby-source-s3-image/, но по-прежнему отсутствует некоторая информация.

gatsby-config.js (отображается только добавленный фрагмент)

{
  resolve: 'gatsby-source-s3-image',
  options: {
    bucketName: 'unlucky',
    domain: null,
    protocol: 'https',
  },
},

index.md (пример сообщения)

---
title: GTX
date: "2019-10-20T22:12:03.284Z"
description: "Vehicle in red and black"
featuredImage: "https://unlucky.s3.us-east-2.amazonaws.com/gtx-car-red-and-black-unlucky.jpg"
---

<img 
  src="https://unlucky.s3.us-east-2.amazonaws.com/gtx-car-red-and-black-unlucky.jpg"
  alt="GTX car shown in black and red"
/>

gatsby-node.js

const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

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

  const blogPost = path.resolve(`./src/templates/blog-post.js`)
  const result = await graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
              }
            }
          }
        }
      }
    `
  )

  const photographyQuery = graphql`
  {
    allS3ImageAsset {
      edges {
        node {
          ETag
          EXIF {
            DateCreatedISO
          }
        }
      }
    }
  }
`

  if (result.errors) {
    throw result.errors
  }

  // Create blog posts pages.
  const posts = result.data.allMarkdownRemark.edges

  posts.forEach((post, index) => {
    const previous = index === posts.length - 1 ? null : posts[index + 1].node
    const next = index === 0 ? null : posts[index - 1].node

    createPage({
      path: post.node.fields.slug,
      component: blogPost,
      context: {
        slug: post.node.fields.slug,
        previous,
        next,
      },
    })
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}

src / pages / index.js

даже не обязательно начать здесь. строки выше экспортируемых не отображаются ниже

export default BlogIndex

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            title
            description
            featuredImage {
              childImageSharp {
                sizes(maxWidth: 630) {
                  ...GatsbyImageSharpSizes
                }
              }
            }
          }
        }
      }
    }
  }
`
...