Search code examples
node.jsreactjsenvironment-variablesenvironment

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.


Solution

  • 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