【问题标题】:Why doesn't the image from the external link work in gatsby?为什么外部链接中的图像在 gatsby 中不起作用?
【发布时间】:2021-04-10 23:30:33
【问题描述】:

对不起,我只是在学习。在某些 gatsby 模板中,我可以插入图片 - 来自 URL 的图片,而在某些模板中,图片不想显示它。

它取决于什么以及如何编辑代码以使 url 工作? (我对graphql的了解比较基础)

这是博客模板的代码:

/** @jsx jsx */
import { jsx } from 'theme-ui'
import { Link, graphql } from "gatsby"
import Img from "gatsby-image"
import { RiArrowRightLine, RiArrowLeftLine } from "react-icons/ri"

import Layout from "../components/layout"
import SEO from '../components/seo';

const styles = {
  'article blockquote': {
    'background-color': 'cardBg'
  },
  pagination: {
    'a': {
      color: 'muted',
      '&.is-active': {
        color: 'text'
      },
      '&:hover': {
        color: 'text'
      }
    }
  }
}

const Pagination = (props) => (
  <div 
    className="pagination -post"
    sx={styles.pagination}
  >
    <ul>
        {(props.previous && props.previous.frontmatter.template === 'blog-post') && (
          <li>
              <Link to={props.previous.frontmatter.slug} rel="prev">
                <p
                  sx={{
                    color: 'muted'
                  }}
                >
                  <span className="icon -left"><RiArrowLeftLine/></span> Previous</p>
                <span className="page-title">{props.previous.frontmatter.title}</span>
              </Link>
          </li>
        )}
        {(props.next && props.next.frontmatter.template === 'blog-post') && (
          <li>
            <Link to={props.next.frontmatter.slug} rel="next">
              <p
                sx={{
                  color: 'muted'
                }}
              >Next <span className="icon -right"><RiArrowRightLine/></span></p>
              <span className="page-title">{props.next.frontmatter.title}</span>
            </Link>
          </li>
        )}
    </ul>
  </div>
)

const Post = ({ data, pageContext }) => {
  const { markdownRemark } = data // data.markdownRemark holds your post data
  const { frontmatter, html, excerpt } = markdownRemark
  const Image = frontmatter.featuredImage ? frontmatter.featuredImage.childImageSharp.fluid : ""
  const { previous, next } = pageContext

  let props = {
    previous,
    next
  }

  return (
    <Layout className="page">
      <SEO
        title={frontmatter.title}
        description={frontmatter.description ? frontmatter.description : excerpt}
        image={Image}
        article={true}
      />
      <article className="blog-post">
        <header className="featured-banner">
          <section className="article-header">
            <h1>{frontmatter.title}</h1>
            <time>{frontmatter.date}</time>
          </section>
          {Image ? (
            <Img 
              fluid={Image} 
              objectFit="cover"
              objectPosition="50% 50%"
              alt={frontmatter.title + ' - Featured image'}
              className="featured-image"
            />
          ) : ""}
        </header>
        
        <div
          className="blog-post-content"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      </article>
      {(previous || next) && (
        <Pagination {...props} />
      )}
    </Layout>
  )
}

export default Post

export const pageQuery = graphql`
  query BlogPostQuery($id: String!) {
    markdownRemark( 
      id: { eq: $id }
    ) {
      id
      html
      excerpt(pruneLength: 148)
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        slug
        title
        description
        featuredImage {
          childImageSharp {
            fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
              ...GatsbyImageSharpFluid
              ...GatsbyImageSharpFluidLimitPresentationSize
            }
            sizes {
              src
            }
          }
        }
      }
    }
  }
`

典型帖子:

---
template: blog-post
title: my title
slug: /plant/bud
date: 2020-05-13 12:37
description: abc
featuredImage: /assets/screen-post-hixmjdah9xhoo-unsplash.jpg (but online image from imgurl png doesnt work)
---


post nr 1

已编辑 ///

plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/static/assets/`,
        name: `assets`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/content/`,
        name: `content`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        gfm: true,
        plugins: [
          netlifyCmsPaths,
          `gatsby-remark-reading-time`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 1024,
              showCaptions: true,
              linkImagesToOriginal: false,
              tracedSVG: true,
              loading: "lazy",
            },
          },
          `gatsby-remark-responsive-iframe`,
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              classPrefix: "language-",
              inlineCodeMarker: null,
              aliases: {},
              showLineNumbers: false,
              noInlineHighlight: false,
              // By default the HTML entities <>&'" are escaped.
              // Add additional HTML escapes by providing a mapping
              // of HTML entities and their escape value IE: { '}': '&#123;' }
              escapeEntities: {},
            },
          },
        ],
      },
    },

【问题讨论】:

    标签: node.js reactjs graphql gatsby


    【解决方案1】:

    在 Gatsby 中,您可以使用带有 src 属性的标准 HTML &lt;img&gt; 标记从外部来源插入图像:

    <img src="https://via.placeholder.com/150" alt="Alt text" width="500" height="600">
    

    如果你想跨外部(或在线)图像保持gatsby-image 的好处,你应该需要使用一些依赖来实现延迟加载和其他功能。

    但是,要使用 gatsby-image,您需要允许 Gatsby 和推断的 GraphQL 架构在文件系统 (gatsby-source-filesystem) 或换句话说,Gatsby需要访问需要解析的图像以创建有效的可查询 GraphQL 模式,该模式将与 gatsby-image 一起使用。

    此外,您需要指定这些图像所属的项目文件夹(设置文件系统):

    const path = require(`path`)
    
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `images`,
            path: path.join(__dirname, `src`, `images`),
          },
        },
        `gatsby-plugin-sharp`,
        `gatsby-transformer-sharp`,
      ],
    }
    

    设置文件系统并处理图像后,将创建一个 GraphQL 节点,并且您可以使用您提供的片段:

    featuredImage {
      childImageSharp {
        fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
          ...GatsbyImageSharpFluid
          ...GatsbyImageSharpFluidLimitPresentationSize
        }
        sizes {
          src
        }
      }
    }
    

    由于 Gatsby 无法直接处理外部图像,因此无法与gatsby-image 一起使用。根据这些图像的来源,某些插件允许您继续使用来自外部来源的gatsby-image(通常来自 Contentful 等 CMS)。

    您可以在Working with images docs 中查看更多文档。

    更新 (01/06/2021)

    在上一个Gatsby version (v2.30) 中,他们添加了一个新的实验性功能,对于support external images in a &lt;StaticImage&gt; component 仍处于测试阶段。要启用它,只需升级到最新的 Gatsby 版本(通过 npmyarn)并在运行脚本中添加以下标志:

    GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby develop
    
    GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby build
    

    然后您可以将绝对 URL 传递给 StaticImage:

    <StaticImage src="https://placekitten.com/400/400" alt="Kittin" />
    

    【讨论】:

    • 感谢您的帮助,它确实亮了很多。好的,但相比之下,在不同的主题中,除了 gatsby-source-filesystem 和外部图像工作之外,没有插件。相比之下,我遇到的问题是你写的所有内容。这就是它的部分外观(我为你编辑的第一篇文章)
    • 正如我所说,有一些 CMS(Prism、DatoCMS、Contentful 等)允许您将 gatsby-image 与外部图像一起使用。我假设您正在谈论的主题使用棱镜(gatsby-remark-prismjs),它是(gatsby-transformer-remark)的插件。在这种情况下,您可以使用gatsby-image,因为源代码允许您
    • 我按照你的指示(远程图像和新鲜的盖茨比(,但我仍然有同样的错误:error GraphQL Error Field "thumbnail" must not have a selection since type "String",我的帖子模板看起来像这样---标题:糟糕的日期: “2017-08-03”缩略图:raw.githubusercontent.com/user/images/img1.png 描述:测试 --- ,但外部图像仍然不起作用。
    • 这个问题通常来自多个来源。从不匹配的依赖版本到将图像放入包含其他类型文件的文件夹中,或者命名错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多