1

I'm new to React and trying to import some images. However, the image I'm using can be of either jpg or png, how do I write code that imports the png if it exists or the jpg if the png doesn't exist, all as one constant similar to how the import keyword is used usually?

import Card from "Card.{png, jpg}"

I've tried the following:

let Card = "";
try {
  Card=require("path-to-png");
} catch(_) {
  try {
    Card = require("path-to-jpg")
  } catch(__) {
    Card = ""
  }
}

But it returns the same error: Module not found: Error: Can't resolve 'path-to-jpg' in '...'

Apoqlite
  • 239
  • 2
  • 21
  • Of course it will throw an error, but the code is free to ignore it. See [Catch an error on requiring module in node.js](https://stackoverflow.com/q/17553386/215552). Of course, that assumes the code is using an actual path to a known location of a file, and not the literal string `"path-to-jpg"`... – Heretic Monkey Aug 04 '22 at 21:06

1 Answers1

2

You can try something like this:

import CardPng from "Card.png"
import CardJpg from "Card.jpg"
const Card = (CardPng ?? CardJpg)

There is no way to import from file1 or file2 for the same declaration name

LDami
  • 31
  • 9
  • Won't this cause the same import error? – Apoqlite Aug 04 '22 at 21:02
  • Why ? There are from different files, and have different names – LDami Aug 04 '22 at 21:04
  • Oh, I don't think I clarified, my bad. It's not both, its only one, either a jpg or a png, not both. If the jpg doesn't exist the CardJpg import doesn't work. – Apoqlite Aug 04 '22 at 21:05
  • Maybe it's possible if it was possible to ignore import errors, but using the above try catch doesn't seem to work. – Apoqlite Aug 04 '22 at 21:07
  • This will cause an import error for the file that doesn't exist. You would need to use a dynamic import (i.e. `const CardPng = await import("Card.png");`) with a try/catch, assuming that even works in React. – Heretic Monkey Aug 04 '22 at 21:08
  • As I said, I don't think it's possible. Look into dynamic import: https://javascript.info/modules-dynamic-imports – LDami Aug 04 '22 at 21:12
  • With Webpack you can specify modules that should be ignored if they fail to resolve by setting `resolve.fallback['packageName']` to `false` - but I'm not sure how it could work with needing to target any and all `.jpg` files. – Slbox Aug 04 '22 at 22:39