Hiimdjango
Hiimdjango

Reputation: 620

set environment variable on build React.js

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.

Upvotes: 0

Views: 197

Answers (2)

Fowad
Fowad

Reputation: 292

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

Upvotes: 0

jinwar
jinwar

Reputation: 386

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

Upvotes: 1

Related Questions