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 ?
CodePudding user response:
You should avoid using dynamic requires as it has bad consequences.
- Metro bundler will not package unused images and dynamic require makes it hard to detect.
- It is covered in the official documentation: React Native - Static Image Resources
- It is also generally not advised by ESLint: eslint-plugin-import/no-dynamic-require
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`);
};
CodePudding user response:
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`)
};