0

Is there any way of extending the process.env.NODE_ENV so that different environment variables are in different builds.

This piece of code process.env.NODE_ENV === 'staging' produces this error This condition will always return 'false' since the types '"production" | "test"' and '"staging"' have no overlap. To my understanding this is because only 'development' | 'production' | 'test' variables are allowed in NODE_ENV.

I was looking at these questions and its answers:

  1. using process.env in TypeScript
  2. This condition will always return 'false' since the types '"development" | "production" | "test"' and '"local"' have no overlap.ts(2367)
  3. Extending process.env variable types in Nodejs with Typescript

I created index.d.ts file in the root directory where package.json file is and added:

declare namespace NodeJS {
  interface ProcessEnv {
     NODE_ENV: 'development' | 'production' | 'staging';
  }
}

Should I include this file in some config?

Is there any way on building the project using command with variables i.e: npm build --staging or react-scripts build --staging so that the code below makes sense:

if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
  url = DEV_URL;
} else if (process.env.NODE_ENV === 'staging') {
  url = STAGING_URL;
}
else if (process.env.NODE_ENV === 'production') {
  url = PRODUCTION_URL;
}
else {
  url = DEV_URL;
}

If you have any suggestions on how to solve this in a different way, please feel free to add them.

Sachihiro
  • 1,597
  • 2
  • 20
  • 46

1 Answers1

0

you can set custom variables in build like:

build:staging: set "REACT_APP_ENVIRONMENT=staging" && npm start

and then in app you can check that

if (!process.env.REACT_APP_ENVIRONMENT || process.env.REACT_APP_ENVIRONMENT === 'development') {
  url = DEV_URL;
} else if (process.env.REACT_APP_ENVIRONMENT === 'staging') {
  url = STAGING_URL;
}
else if (process.env.REACT_APP_ENVIRONMENT === 'production') {
  url = PRODUCTION_URL;
}
else {
  url = DEV_URL;
}
Wraithy
  • 1,722
  • 1
  • 5
  • 13
  • Do you have any idea why `(process.env.REACT_APP_ENVIRONMENT === 'staging')` is false? When I log the parameter, it logs as staging, but somehow it ends up in the final else clause, and the url is the base url even though it should be the staging url – Sachihiro Oct 17 '22 at 11:40
  • which OS are u using? this one "set" is for windows, you must change it according to OS, but better solution would be to use `.env` files. source: https://create-react-app.dev/docs/adding-custom-environment-variables/ – Wraithy Oct 17 '22 at 12:17
  • I am on windows, fixed. – Sachihiro Oct 17 '22 at 12:18