How to set build .env variables when running create-react-app build script?

前端 未结 4 1763
后悔当初
后悔当初 2020-12-07 16:19

I\'m using the following environment variable in my create-react-app:

console.log(process.env.REACT_APP_API_URL) // http://localhost:5555

I

4条回答
  •  既然无缘
    2020-12-07 16:45

    I imagine you got this working by now, but for anyone else that finds this, you set your default environment variables in a .env file at the root of your "create-react-app" project.

    To separate out the variables used when using npm start and npm run build you can create two more env files - .env.development and .env.production.

    npm start will set REACT_APP_NODE_ENV to development, and so it will automatically use the .env.development file, and npm run build sets REACT_APP_NODE_ENV to production, and so it will automatically use .env.production. Values set in these will override the values in your .env.

    If you're working with other people, and have values specific to your machine only, you can override values in .env.development and .env.production by adding those values to a new file - .env.development.local and .env.production.local respectively.

    EDIT: I should point out that the environment variables you have set must start with "REACT_APP_", eg. "REACT_APP_MY_ENV_VALUE".

    EDIT 2: if you need more than just development, and production, use env-cmd, as specified by this comment.

提交回复
热议问题