create react app not picking up .env files?

前端 未结 10 2076
醉话见心
醉话见心 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:27

    Make sure your .env file is in the root directory, not inside src folder.

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

    Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:

    "scripts": {
        "build:local": "env-cmd -f ./.env.production.local npm run build",
        "build:production": "env-cmd -f ./.env.production npm run build"
      }
    

    In your package.json file.

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

    If you want to use multiple environment like .env.development .env.production

    use dotenv-cli package

    add .env.development and .env.production in project root folder

    and your package.json

    "scripts": {
        "start": "react-app-rewired start",
        "build-dev": "dotenv -e .env.development react-app-rewired build",
        "build-prod": "dotenv -e .env.production react-app-rewired build",
        "build": "react-app-rewired build",
        "test": "react-app-rewired test --env=jsdom",
        "eject": "react-scripts eject"   
    },
    

    then build according to environment like

    npm run-script build-dev 
    
    0 讨论(0)
  • 2020-12-12 20:29

    As of latest react-scripts (3.2.0) it's a simple as putting say

    PORT=4000
    BROWSER=none
    

    in your .env or .env.development file (..etc) which is supposed to be in the root folder.

    It will NOT work with then REACT_APP prefix (the docs are outdated I guess) and it does NOT require any extra npm packages (react-scripts already includes dotenv 6.2.0)

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

    If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.

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

    And remember not to have semi-colon after the API key in the env-file.

    REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';

    should be

    REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'

    that was my error

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