3

我一直在关注本教程https://www.gatsbyjs.org/packages/gatsby-image/#art-directing-multiple-images但普通人不可能编写 50 行代码来添加图像:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => {
  // Set up the array of image data and `media` keys.
  // You can have as many entries as you'd like.
  const sources = [
    data.mobileImage.childImageSharp.fluid,
    {
      ...data.desktopImage.childImageSharp.fluid,
      media: `(min-width: 768px)`,
    },
  ]

  return (
    <div>
      <h1>Hello art-directed gatsby-image</h1>
      <Img fluid={sources} />
    </div>
  )
}

export const query = graphql`
  query {
    mobileImage: file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        fluid(maxWidth: 1000, quality: 100) {
          ...GatsbyImageSharpFluid
        }
      }
    }
    desktopImage: file(
      relativePath: { eq: "blog/avatars/kyle-mathews-desktop.jpeg" }
    ) {
      childImageSharp {
        fluid(maxWidth: 2000, quality: 100) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`

我的问题是,你如何保持理智并在 gatsby 中使用图像?

这个例子有很多问题:

  • 导入和使用相距甚远,理想情况下应该相近(因此如果从html中删除,需要记得从graphql中删除)
  • 样板的数量是巨大的。想象一下,您需要 2 张图片...
  • 导入图像时没有自动完成。开发人员真的输入了图像的完整路径吗?这似乎是很多工作。重命名看起来也有风险。(我正在使用intellij。)

对于其他使用打字稿并希望通过仅过滤图像来提高性能的人:

import {graphql, useStaticQuery} from 'gatsby'
import Img from 'gatsby-image'
import React from 'react'

interface Props {
  // @todo: convert to enum
  relativePath: string;
  alt: string;
}

export const Image: React.FC<Props> = (props) => {
  const {relativePath, alt} = props

  const images: { data: { edges: Array<{ node: { relativePath: string, default: { fluid: any } } }> } } = useStaticQuery(graphql`
    query ImageQuery {
      data: allFile(filter: {sourceInstanceName: {eq:"images"}}) {
        edges {
          node {
            relativePath
            default: childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `)

  const image = images.data.edges.find(n => {
    return n.node.relativePath.includes(relativePath)
  })

  if (!image) {
    throw new Error(`Image not found`)
  }

  return (
    <Img alt={alt} fluid={image.node.default.fluid} />
  )
}

添加源实例名称

/**
 * From:
 *  - https://github.com/ChristopherBiscardi/gatsby-mdx/issues/105
 *  - https://github.com/gatsbyjs/gatsby/issues/1634
 */
export const onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const parent = getNode(node.parent)
    if (parent.internal.type === 'File') {
      createNodeField({
        name: `sourceInstanceName`,
        node,
        value: parent.sourceInstanceName,
      })
    }
  }
}

和插件配置

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: props.imageRootFolder,
        name: 'images',
      },
    },
4

1 回答 1

2

我使用通用Image组件:

import React from "react"
import Img from "gatsby-image"
import { useStaticQuery, graphql } from "gatsby"

export default (props) => {

  const { filename, type = 'default', alt, sizes = '(max-width: 400px) 100px, (max-width: 800px) 200px, 400px' } = props;

  const images = useStaticQuery(graphql`
    query ImageQuery {
      data: allFile {
        edges {
          node {
            relativePath
            default: childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
            square: childImageSharp {
              fluid(maxWidth: 600, maxHeight: 600) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `);

  const image = images.data.edges.find(n => {
    return n.node.relativePath.includes(filename);
  });

  if (!image) {
    return null;
  }

  return (
    <Img alt={alt} fluid={{
      ...image.node[type].fluid,
      sizes: sizes,
    }} />
  )
}

然后我传递文件名和替代文本(以及可选的类型和大小)。

 <Image alt="Gravity does not apply to cats" type="square" filename="cat-defies-gravity.png" />

我同意这是一种解决方法,直到我们得到类似Querying 2.0的东西。如果您阅读该页面,您将看到您的问题作为示例。

于 2020-05-01T21:32:05.607 回答