Generic Gatsby Image Component without querying for each image
One of the coolest features of Gatsby is the
gatsby-image component. Here is why I love using
- 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
srcsetattribute 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:
gatsby-imagedocs, especially useful if you want to use the CSS rule
fit-content: coveron the image)
Credit to the original idea and code goes to Noah Gilmore. Here’s my extended version:
- make sure to have
- add gatsby-image-sharp configuration to gatsby-config.js
- place your images in the directory
importthe generic image component (code form above)
- use it like this:
<Image filename="myimage.jpg" />
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.