0

Description

I'm just trying to import a simple img into my gatsby application, from a path entry in my json file.

Steps to reproduce

When I'm using

<img
    alt="..."
    src={require("assets/images/todd-logo.svg")}
/>

The image gets imported and rendered as expected. But when I try to import the image with a variable as a path:

<img alt="..." src={require(`${props.image}`)} />

I get an error similar to:

Error: Cannot find module 'assets/images/accomodation-room1.png'

This happens even if I use assets/images/todd-logo.svg as the variable value in the json file, in the same js file I'm working on. This problem arises when I use a variable as a path.

I have added a jsconfig.json with the following parameters to deal with paths in my project, while using the plugin 'gatsby-plugin-resolve-src'(maybe the problem it's here...?)

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "*": ["src/*"],
      "assets": ["src/assets"]
    }
  }
}

1 Answers1

0

You don't need any plugin to make a dynamic asset importation with your approach, I would remove it. You should only be aware that the paths are relative to the component that is importing the image, not to the JSON entry file. Check the relativity with the slashes (/) and the levels (..).

Dealing with SVG is another war, they should be imported as a component to allow the render of the inner SVG's tags. You can follow this approach from another StackOverflow question.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67