wayfare
wayfare

Reputation: 1850

How to make build for react app for different stages?

I have a single page application which is a react app. I am using webpack for it. I am facing problem in configuring server API URL for every stage like test, beta and prod.

Is there some standard way of doing it?

Upvotes: 1

Views: 1446

Answers (2)

Mohit Mutha
Mohit Mutha

Reputation: 3001

Create a .env and add your variables there ensuring that they are prefixed with REACT_APP e.g. REACT_APP_SERVER_URL=https://example.com

You can create multiple env files one each for dev, prod, test etc. like .env.local, .env.prod

The env files injected from your npm commands

npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env

Use the variable in your code like

if (process.env.NODE_ENV !== 'production') {
    analytics.disable();
 }

OR

 <b>{process.env.NODE_ENV}</b>

Refer https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-development-environment-variables-in-env

Upvotes: 1

PlayMa256
PlayMa256

Reputation: 6841

Do that based on NODE_ENV.

declare an url file in your application for the basepath of it.

const baseURL = (__DEV__) ? url1 : url 2;

or a switch statement, does'nt matter.

Do be able to have access to these variables, you have to use DefinePlugin from webpack.

new webpack.DefinePlugin({
  envType: JSON.stringify(process.env.NODE_ENV)
})

or something like that...

Upvotes: 0

Related Questions