gatsby-image: difference between childImageSharp vs imageSharp

故事扮演 提交于 2019-12-10 02:11:47

问题


I'm using gatsby-image to handle automatically handle different image sizes. It works great.

However, in the docs of gatsby-image, one example uses imageSharp in graphql to get different image sizes, while another example uses childImageSharp. I was curious what the difference between the two are?

I assume it has to do with either gatsby-transformer-sharp or gatsby-plugin-sharp, but the docs for those plugins don't have any info on that either.


回答1:


It's been a while since this question was asked, but I hope to give a direct answer to the question 'what's the different between imageSharp and childImageSharp':

Different between imageSharp & childImageSharp

They are always the same type of node, which is ImageSharp. The difference is the reference point.

In a typical gatsby blog, all files will be first processed with gatsby-transformer-file-system. Each file will get a node with information such as what type of file it is, then, a plugin like gatsby-transformer-sharp will pick up the node with the relevant type/extension, then process it further and create a new node:

File                                image.png

                                        |

                                   create a node with
gatsby-transformer-file-system ->  "type": "File",
                                   "extension": "png"

                                        |

                                   whenever see a node 
                                   with a valid image extension,
gatsby-transformer-sharp       ->  create a node with
                                   "type": "ImageSharp"
                                   that contains info of images
                                   processed by `gatsby-plugin-sharp`

Whenever this happens, a parent-child relationship is created between the original File node and the ImageSharp node. The child ImageSharp node will be queriable on the File node with the name childImageSharp.


File                                ImageSharp
  |--id: 1                              |--id: 2
  |--children                           |--parent
  |     `--[ id: 2 ]                    |    `--id: 1
  `--childImageSharp                    |--fluid
        |--id: 2                       ...
        |--fluid
       ...

It means you can query the same ImageSharp node in at least 2 ways:

1. From the File node

ImageSharp node doesn't contain any info about its location in the file system, so if you want to get an image from folder src/X, you'd need to query it like:

query {
  // relativePath is relative to the folder set in `gatsby-transformer-file-system`
  file ( relativePath: { eq: "src/X"} ) {
    childImageSharp {
      id
      fluid {
        src
      }
    }
  }
}

2.Directly get the ImageSharp

Perhaps somehow you know the exact id of the ImageSharp node. You can get it by:

{
  imageSharp (id: {eq: "2"}) { // not a real id
    id
    fluid {
      src
    }
  }
}

You can also query multiple images from allFile, or allImageSharp.

This will return with an error:

// error
{
  childImageSharp {
    id
  }
}

Other plugins share the same kind of relationship as well. You can also find a childMardownRemark node on the File type, that resolve to a MarkdownRemark node.

It doesn't have anything to do with gatsby-image -- it's just different way to resolve to the same node.




回答2:


Great question, Sharp is an amazing tool and can do so much with any JavaScript application. It also has extensive documentation its self I suggested looking in to.http://sharp.dimens.io/en/stable/

First imageSharp can be used in a variety of ways especially with the Transform. But here is an simple example of just utilizing imageSharp in the Gatsby universe. Imagine this is index.js in the pages folder and there is route of home

import { Home } from 'routes/Home/Home'

/* eslint no-undef: "off" */
export const pageQuery = graphql`
  query HomeQuery {
    image1Image: imageSharp(id: { regex: "/image1.png/" }) {
      sizes(quality: 100) {
        ...GatsbyImageSharpSizes_withWebp
      }
    }
    image2Image: imageSharp(id: { regex: "/image2.png/" }) {
      sizes(quality: 100) {
        ...GatsbyImageSharpSizes_withWebp
      }
    }
    image3Image: imageSharp(id: { regex: "/image3.png/" }) {
      sizes(quality: 100) {
        ...GatsbyImageSharpSizes_withWebp
      }
    }
}
`
export default Home

Then a childImageSharp you would use this for defining image styles throughout an application, for instance you have a folder called types the path would be src/types/images.js for example in this file you would define the resolution and size of the image and the datasets associated. Then export childImageSharp as you plan to reuse the child over and over in different parts of your app.

// @flow

export type GatsbyImageResolutions = {
    resolutions: {
        base64?: string,
        height: number,
        src: string,
        srcSet: string,
        width: number,
    },
};

export type GatsbyImageSizes = {
    sizes: {
        aspectRatio: number,
        base64?: string,
        sizes: string,
        src: string,
        srcSet: string,
    },
};

export type Image = {
    childImageSharp: GatsbyImageResolutions | GatsbyImageSizes,
};

Now here is an example of the power of transforming an image. This example is a returned with a ImageURL via the WordPress REST-api to a standard href=link to a link. Well Resizing and reshaping the image with childIamgeSharp! Both existing in one file src/post/post.js

/**
     * Transform internal absolute link to relative.
     * 
     * @param {string} string The HTML to run link replacemnt on
     */
    linkReplace(string) {
        // console.log(string)
        const formatted = string.replace(
            /(href="https?:\/\/dev-your-image-api\.pantheonsite\.io\/)/g,
            `href="/`
        )

        return formatted
    }

    render() {
        const post = { ...this.props.data.wordpressPost }
        const headshot = { ...this.props.data.file.childImageSharp.resolutions }
        const { percentScrolled } = { ...this.state }
        const contentFormatted = this.linkReplace(post.content)

        return (
            <div ref={el => (this.post = el)}>
                <div className={styles.progressBarWrapper}>
                    <div
                        style={{ width: `${percentScrolled}%` }}
                        className={styles.progressBar}
                    />
                </div>

                <div className={styles.post}>
                    <h1
                        className={styles.title}
                        dangerouslySetInnerHTML={{ __html: post.title }}
                    />

                    <div
                        className={styles.content}
                        dangerouslySetInnerHTML={{ __html: contentFormatted }}
                    />

                    <Bio headshot={headshot} horizontal={true} />
                </div>
            </div>
        )
    }
}

Post.propTypes = {
    data: PropTypes.object.isRequired,
}

export default Post

export const postQuery = graphql`
    query currentPostQuery($id: String!) {
        wordpressPost(id: { eq: $id }) {
            wordpress_id
            title
            content
            slug
        }
        file(relativePath: { eq: "your-image-headshot.jpg" }) {
            childImageSharp {
                resolutions(width: 300, height: 300) {
                    ...GatsbyImageSharpResolutions
                }
            }
        }
    }

Let me know if this helps you,If not I would be glad to help explain in more detail. As Sharp and Gatsby are both subjects I am very Passionate about and I deal with Sharp almost daily in my full-time Job.




回答3:


Sorry for the delay in response & maybe you have a better understanding now but figured I would follow up here.

Referring back to Gatsby 1.0 as when I answered this question 2.0 was not released yet. But a few things have to be taken in to account 1 where is the image path? and 2 is the image coming from an MD file for a blog post or a assets file or API?

This is what a component using gatsby-image looks like: (this is from the Gatsby v1 Docs)

import React from "react"
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <Img fixed={data.file.childImageSharp.fixed} />
  </div>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
      childImageSharp {
        # Specify the image processing specifications right in the query.
        # Makes it trivial to update as your page's design changes.
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

Gatsby-image directly uses components from the Sharp library. As you see above gatsby-image uses childImageSharp referencing the GraphQL query where you define the file path, size, etc of the image. It would be considered a child because the original or "origin" image in the filesystem is a different makeup in size or file type.

ImageSharp can be used when defining the node or a general sense of the image in a component or layout as no specific path for an image is being called directly.



来源:https://stackoverflow.com/questions/50141031/gatsby-image-difference-between-childimagesharp-vs-imagesharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!