Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

438
Visualizações
'Cannot find module' error dynamically importing image

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda