DEV Community

Cover image for Need help to improve my usage of gatsby-image
jan paul
jan paul

Posted on

Need help to improve my usage of gatsby-image

Hello fellow Gatsby'ers. Today i am comming with a question to you. I need to improve my bundle size, and therefore i want to rewrite my gatsby-image wrapper to be more efficient.

Consider my bundle
Alt Text

BUT: the 150 images itself are only 14MB in total, which means gatsby bloats it like crazy.

I know my code smell in terms of BIG-O, but, my poor excuse, i didn't knew another way than mapping over the result. Can you guys help me to improve here, considering:

const ImageLarge = props => {
  return (
    <StaticQuery
      query={graphql`
        query {
          allFile(filter: { sourceInstanceName: { eq: "assets" } }) {
            edges {
              node {
                relativePath
                name
                childImageSharp {
                  fluid(maxWidth: 600, quality: 100) {
                    ...GatsbyImageSharpFluid
                  }
                }
              }
            }
          }
        }
      `}
Enter fullscreen mode Exit fullscreen mode

and here now my pile of shame:

 const image = data.allFile.edges.find(n => {
          return n.node.relativePath.includes(`${path + props.src}`)
        })

        if (!image) return null
Enter fullscreen mode Exit fullscreen mode

Btw, my problem are comming from not beeing able to parametrize my static gqlquery with arguments, so i took all images, mapped over and returned only the image that i needed. horrible inifficnient.

Why cant i do something like this?

const ImageLarge = props => {
  return (
    <StaticQuery
      query={graphql`
        query {
          allFile(filter: { sourceInstanceName: { eq: `assets/${name}.png` } }) {
            edges {
              node {
                relativePath
                name
                childImageSharp {
                  fluid(maxWidth: 600, quality: 100) {
                    ...GatsbyImageSharpFluid
                  }
                }
              }
            }
          }
        }
      `}
Enter fullscreen mode Exit fullscreen mode

I asked google and found this, which describes my problem perfectly, but offers no solution

"Believe it or not you cannot create a fully dynamic image component using a gastby-image without risking a (possibly very large) bloat in your bundle size. The problem is that static queries in Gatsby do not support string interpolation in it's template literal."

what-is-the-best-way-to-display-all-pictures-of-a-directory-in-a-gatsby-project

If one you could help me to solve this problem, i'd be glad and i also think, that we should write about it here, so others can find this googeling.

May the code be with you 🙏

Discussion (0)