Home > Blockchain >  Setting up React environment variables for dev and local
Setting up React environment variables for dev and local

Time:02-10

I am new to react and setting up environment variables for my project. Here is what I did..

  1. added .env-cmdrc.json as follows

    {
     "development":{
     "REACT_APP_BASE_URL": "https://servername:port/"
     },
     "staging":{
     "REACT_APP_BASE_URL": "http://servername:port/"
     },
      "local":{
      "REACT_APP_BASE_URL": "http://localhost:port/"
      }
     }
    
  2. installed npm

npm install env-cmd or npm install -g env-cmd

  1. edited package.json as follows:

     "start:development": "env-cmd -e development react-scripts start",
     "start:staging": "env-cmd -e staging react-scripts start",
     "start:local": "env-cmd -e local react-scripts start",
     "build:development": "env-cmd -e development react-scripts build",
     "build:staging": "env-cmd -e staging react-scripts build",
    
  2. tried - npm run start:development

    was giving me env-cmd error

  3. again ran

    npm install env-cmd

  4. Now tried - npm run start:development

Failed to find .rc file at default paths: [./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

I am doing it first time and would appreciate any help..what am I missing here..

CodePudding user response:

I would suggest using dotenv package instead of env-cmd.

  1. install the package - npm i dotenv
  2. Create a environment file in your root directory - .env
  3. Declare a variable - REACT_APP_URL=http://localhost/....
  4. Use the variable - process.env.REACT_APP_URL

In order to start the React application you need to check your package.json file and make sure it contains something like this:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

If that's in place you can run the following command: npm start


Now you can start coding :)

CodePudding user response:

I tried your code, but it works well.
Check your code, ensure the location of your config file .env-cmdrc.json, it should be placed under root dict of your project (the same level with package.json)

  • Related