0

I am trying to have a custom environment variable on build with React, by default it's set to production but I'm trying to have a custom QA build with a custom variable. Ps : Project is ejected, is there anyway I can manage to do that without messing with my webpack configs.

1
  • 2
    You can use this: new webpack.DefinePlugin({ "YOUR_VARIABLE": JSON.stringify("value of your variable") }) in your webpack config Commented Jul 8, 2020 at 15:10

2 Answers 2

1

This is how I do it (I am using react-scripts) :

In package.json I have those scripts :

"build:prototype": "env-cmd -f ./.env.prototype npm run-script build",
"build:demo": "env-cmd -f ./.env.demo npm run-script build",
"build:local": "env-cmd -f ./.env.local npm run-script build",
"build:production": "env-cmd -f .env.production npm run-script build",

and I call them just like any other : npm run build:prototype for example

Hope it helps

Edit: of course I have those .env files at the root of the project

Sign up to request clarification or add additional context in comments.

Comments

0

Use webpack's Define Plugin

new webpack.DefinePlugin({
  "CUSTOM_VARIABLE": JSON.stringify("whatever you want to set it to")
})

And wherever you need to change certain things in your app, you can check the value of process.env.CUSTOM_VARIABLE and act according to its value. If there are only a few places that depend on this variable, this will work fine. If there are more, it might be worth looking into other approaches, such as React's Context Hook API

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.