5

I want to optimize all the images on my Gatsby site and to achieve that I have installed the gatsby-image-plugin.

For the dynamic images, I am using the GatsbyImage Component and everything is working fine, no issues here.

The problem is when I want to render static images using the StaticImage Component.

Here is an example:

import laptop from '@images/laptop.png';

If I import the image and I use it this way:

<img src={laptop} alt='laptop' />

The image shows up correctly on the browser, but if I try to do this:

import { StaticImage } from 'gatsby-plugin-image';
<StaticImage src={laptop} alt='laptop' />;

The image is not showing up on the browser and I get the following message in the console:

Image not loaded /static/laptop-5f8db7cd28b221fc1a42d3ecd6baa636.png

And this error in the terminal:

Could not find values for the following props at build time: src Image not loaded /static/laptop-5f8db7cd28b221fc1a42d3ecd6baa636.png

I have tried to pass as src a link of a random image from the internet and the image was displayed on the browser! Why is it not working when I use the image that I have in my assets folder?

PS; Reading the plugin documentation I saw that there are some restrictions like you cannot pass images that are coming from the props, but this is not the case! I am importing the image directly from the assets folder.

Any leads, please? Thank you in advance.

tateccf
  • 115
  • 1
  • 9

1 Answers1

3

PS; Reading the plugin documentation I saw that there are some restrictions like you cannot pass images that are coming from the props, but this is not the case! I am importing the image directly from the assets folder.

You're importing the image from your assets folder, but you're still passing it to StaticImage as a prop. The correct usage is as follows:

<StaticImage src='@images/laptop.png' alt='laptop' />

Per the Gatsby Image Plugin documentation, src must be type string. You're currently passing an object {laptop}. Change it to a string with the images file path and it will display.

  • 1
    Hi, thank you for the answer. The src that I am currently passing is not an object, it is a string. Indeed, If I console.log it, the output is: "/static/laptop-5f8db7cd28b221fc1a42d3ecd6baa636.png" . Anyway, I have tried to pass it like you said and it didn't work :( – tateccf Jul 31 '21 at 21:21
  • 3
    Have you tried directly referencing the filepath w/o the folder alias? `` – Snappy Web Design Jul 31 '21 at 21:51
  • '@images/...' isn't working for me, directly referencing the image src='../images/...' doesn't work either. Am I missing something? – Punter Bad Feb 28 '23 at 17:29