I am creating a react app with express backend. In this code, I am fetching a path to an image relative to my 'assets' folder, and then dynamically importing it. Where I'm having trouble is with this import statement. I have the line const importURL: string = `../../${json.imgURL}.png` . When I await the import() passing in importURL, i keep getting the error:
Uncaught (in promise) Error: Cannot find module '../../assets/images/backgrounds/home/background1.png'
at Home|lazy|groupOptions: {}|namespace object:5:1
at async getBackground (index.tsx:17:1)
But, the problem is, if I statically write out the exact same path into a string using '' instead of ``, it works.
I am wondering if it has to do with not creating the string statically, but I wouldn't think that would really be the problem because it shows the correct path in the error.
My full function is below. Uncommenting the commented line and commenting the two above it makes the program work as expected, but then I have to hard code the image I'm importing.
async function getBackground(index: number) {
const response: Response = await fetch(`${baseURL}home-background?i=${index}`)
const json = await response.json()
const importURL: string = `../../${json.imgURL}.png`
const curBackground = await import(importURL)
// const curBackground = await import(
// '../../assets/images/backgrounds/home/background3.png'
// )
setBackground(curBackground.default)
}
Any help is appreciated.