Martin Grubinger, a web developer from Austria

Generic Gatsby Image Component without querying for each image

gatsby

One of the coolest features of Gatsby is the gatsby-image component. Here is why I love using gatsby-image:

  • Blur-up technique: When the page loads, the site only loads a tiny blurred version of the image. As the image enters the viewport, the target resolution loads. This leads to quicker page loads while still having something visible while the image loads. (see this demo)
  • Optional placehoder images as traced SVGs: Instead of using a tiny blurred image, you can also use a traced path outline of the image while the image is loading.
  • Automatically creates different sizes for the image and uses those for the srcset attribute including the tiny blurred version.
  • Generates webp for supporting browsers (if configured)
  • See the docs for a detailed description: https://www.gatsbyjs.org/packages/gatsby-image/

Although it is amazing what you get out of the box using gatsby-image it feels a bit cumbersome to me to write a GraphQL query for each and every image I want to use on a page. This slows down my development workflow.

I did quite a lot – of research and found this article by Noah Gilmore: https://noahgilmore.com/blog/easy-gatsby-image-components/

This is exactly what I was looking for! Simply import the component and use it like this:

<Image filename="image.png" />

I extended the component a bit, to allow these additional props:

  • style
  • imageStyle (see gatsby-image docs, especially useful if you want to use the CSS rule fit-content: cover on the image)
  • className

Credit to the original idea and code goes to Noah Gilmore. Here’s my extended version:

https://gist.github.com/mgrubinger/4b5770c5aec1b1670f839ab9acb14649

Usage

  • make sure to have gatsby-image and gatsby-image-sharp installed
  • add gatsby-image-sharp configuration to gatsby-config.js code here
  • place your images in the directory src/images/
  • import the generic image component (code form above)
  • use it like this: <Image filename="myimage.jpg" />

Conclusion

For me this approach drastically improved my workflow with images in gatsby. The only drawback I see is that all images in your images directory will be transformed, so you might be careful to not throw in too many unused images otherwise build time will go up.

Let me know what you think about this approach: @mgrubinger

Again, thanks to Noah Gilmore.