0

I've got an environment file.

Like the title says, I want to build the path for my images based on the config setup, like so :

const images = {
      logo: require(`./${Config.BRAND}/images/logo_${Config.BRAND}.png`)
    };

Unfortunately, it does not work.

Is there any other way to achieve it ?

10
  • 1
    Did you maybe forget the extension? (.png, .jpg, ...) Commented Oct 27, 2021 at 12:49
  • If you use dotenv you can achieve this. Commented Oct 27, 2021 at 12:50
  • Dynamic imports is an anti-pattern github.com/import-js/eslint-plugin-import/blob/v2.22.1/docs/… Commented Oct 27, 2021 at 12:53
  • @enzo in react-native every image is a module (more or less). It's the official way to load local images: reactnative.dev/docs/image. Commented Oct 27, 2021 at 12:55
  • 1
    @Erenn How would this solve the problem? I don't see how this has anything to do with JSharles question. Commented Oct 27, 2021 at 12:56

2 Answers 2

1

You should avoid using dynamic requires as it has bad consequences.

You can use if-else (or simply ternary) or switch statement to get the image you want to use.

const images = {
  logo: Config.BRAND === 'brand1' ? require(`./brand1/images/logo_brand1.png`) : require(`./brand2/images/logo_brand2.png`);
};
Sign up to request clarification or add additional context in comments.

6 Comments

Indeed, this method works fine but the dynamic require would reduce a lot the amount of code.
I don't think this applies here. Static code analysis is generally not done on images. I would say you can ignore/disable this eslint rule at that position.
Most likely images would not be copied to bundle because metro bundler will think those images are not used because of dynamic require.
@MauriceNino actually, metro bundler doesn't copy the unused images to the release build, and dynamic require makes it hard to detect.
Safe to say, you are right @UgurEren :) stackoverflow.com/questions/30854232/… You should however extend your answer to include the reason why it does not work.
|
-1

Create a .env file in the root of project. Put dynamic brand there.

BRAND=Your_dynamic_link

install than import dotenv module

require('dotenv').config()

Than you can access that environment

const images = {
  logo: require(`./${process.env.BRAND}/images/logo_${process.env.BRAND}.png`)
};

2 Comments

That is actually exactly what I'm doing , but the require does not accept that.
Can you access the env variable? Weird.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.