Home > Enterprise >  In Javascript, how can I dynamically construct a path within a require()?
In Javascript, how can I dynamically construct a path within a require()?

Time:10-27

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.

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`)
};
  • Related