create react app not picking up .env files?

前端 未结 10 2077
醉话见心
醉话见心 2020-12-12 19:52

I am using create react app to bootstrap my app.

I have added two .env files .env.development and .env.production in the root.

相关标签:
10条回答
  • 2020-12-12 20:34

    Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.

    Source: Github

    0 讨论(0)
  • For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:

      "scripts": {
        "start": "env-cmd .env.development react-scripts start",
        "build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
      }
    

    In your project root you have to create two files with the same env variables but with different values:

    .env.development
    .env.production
    

    Then exclude them from public. For this in your .gitignore file add two lines:

    .env.development
    .env.production
    

    So this is a proper way to use different env variables for dev and prod.

    0 讨论(0)
  • 2020-12-12 20:40

    I was having the same problem, but it was because I had my .env file in YAML format instead of JS.

    It was

    REACT_APP_API_PATH: 'https://my.api.path'
    

    but it needed to be

    REACT_APP_API_PATH = 'https://my.api.path'
    
    0 讨论(0)
  • 2020-12-12 20:46

    With create-react-app, you need to prefix REACT_APP_ to the variable name to be able to access it.

    Example:

    REACT_APP_API_URL=http://localhost:3000/api
    REACT_APP_CALLBACK_URL=http://localhost:3005/callback
    

    See more info here

    0 讨论(0)
提交回复
热议问题