Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react load different .env for local, dev, and prod

// create 4 env files to represent local, dev, qa, prod & name them with
// the convention of .env.<environment> e.g. local env would be .env.local
// tldr you should have 4 files in the repo root named:
// .env.production, .env.development, .env.qa, and .env.local 

// react env vars should be prefixed with `REACT_APP` - this allows you
// to create envs based around react without interfering with node. 

// Add the code below to your package.json scripts object.
// we're telling shell to run a file, which uses . to run the contents
// of the given env file making them available to node. The same as
// setting each env var on the cmd prior to running node. Test locally
// by adding REACT_APP_NAME=TEST to your .env.local & using the node repl 
// by running: sh -ac '. ./.env.local; node' & inside the node repl you
// can access the env var process.env.REACT_APP_NAME which equals "TEST".
"scripts": {
    "build:local": "REACT_APP_ENV=local npm run build",
    "build:dev": "REACT_APP_ENV=development npm run build",
    "build:qa": "REACT_APP_ENV=qa npm run build",
    "build:prod": "REACT_APP_ENV=production npm run build",
    "build": "sh -ac '. ./.env.${REACT_APP_ENV}; node scripts/build.js'",
    "start:local": "REACT_APP_ENV=local npm run start",
    "start:dev": "REACT_APP_ENV=development npm run start",
    "start:qa": "REACT_APP_ENV=qa npm run start",
    "start": "sh -ac '. ./.env.${REACT_APP_ENV}; NODE_ENV=development node scripts/start.js'"
}
 
PREVIOUS NEXT
Tagged: #react #load #prod
ADD COMMENT
Topic
Name
2+8 =