找不到gatsby图像svg

时间:2018-12-05 08:58:33

标签: svg gatsby

尝试以这种方式加载SVG图像时:

export const query = graphql`
    query {
        fileName: file(relativePath: { eq: "logo_large.svg" }) {
            childImageSharp {
                fluid(maxWidth: 1060) {
                    ...GatsbyImageSharpFluid_withWebp_tracedSVG
                }
            }
        }
    }
`

我得到TypeError: Cannot read property 'childImageSharp' of null

如果我尝试完全相同但使用.jpg或.png图像,则它可以工作,因此相对路径必须正确。 我应该特别考虑SVG吗?

4 个答案:

答案 0 :(得分:2)

  

“出于明显的原因,此插件不支持SVG,它们是   向量并自动调整其大小,而无需   像这样的插件”

正确。我对字段的要求是所有三个或更多类型,例如png + jpg + svg,因此您必须使用gatsby-image动态地处理它,或者不使用。您可以通过在查询中添加extension和publicURL来解决此问题:

  ...
  image {
    childImageSharp {
      fluid(maxWidth: 500, quality: 92) {
        ...GatsbyImageSharpFluid
      }
    }
    extension
    publicURL
  }
  ...

然后,在PreviewCompatibleImage中,添加如下内容:

  // svg support
  if (!childImageSharp && extension === 'svg') {
    return <img style={imageStyle} src={publicURL} alt={alt} />
  }

信贷转到github上的andresmrm:https://github.com/gatsbyjs/gatsby/issues/10297#issuecomment-464834529

答案 1 :(得分:2)

我知道这是一个古老的问题,答案已被接受,但我认为我可能会为他人的利益添加另一种解决方案。我在以下位置找到了此解决方案:https://github.com/gatsbyjs/gatsby/issues/10297

import yourSVG from './logo_large.svg'

const Home = () => <><img src={yourSVG} /></>

答案 2 :(得分:1)

不知道这是否有帮助,但是如果您正在寻找一个通用的动态Image组件,该组件需要一个自定义文件名并采取相应的措施,那么我可以将其组合起来:

此方法认为您的images文件夹中有一个src文件夹,其中包含所有图像。

const Image = ({ filename, alt }) => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {

      // Handles SVG extension
      const extension = filename.match(/[^\\]*\.(\w+)$/)[1]
      if (extension === "svg") {
        return <img src={require(`../images/${filename}`)} alt={alt}/>
      }

      // Finds your image among all
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(filename)
      })

      if (!image) {
        return null
      }
      return (
        <Img alt={alt} fluid={image.node.childImageSharp.fluid}/>
      )
    }}
  />
)

请注意,此操作未优化,并且会查询您所有的图像。如果您试图以各种可能的方式优化性能,那么这并不是最佳选择。

答案 3 :(得分:0)

此插件不支持SVG,原因很明显,它们是矢量的,不需要像这样的插件即可自动调整大小