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

前端 未结 4 1771
后悔当初
后悔当初 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:57

    You can use the process.env.NODE_ENV like so:

    const apiUrl = process.env.NODE_ENV === 'production' ? process.env.REACT_APP_PROD_API_URL : process.env.REACT_APP_DEV_API_URL;
    

    You would need to have REACT_APP_PROD_API_URL and REACT_APP_DEV_API_URL set.

    Or, if the production URL is always the same, you could simplify it:

    const apiUrl = process.env.NODE_ENV === 'production' ? 'https://example.com' : process.env.REACT_APP_DEV_API_URL;
    

    Create React App sets the NODE_ENV to 'production' for you on build, so you don't need to worry about when to set it to production.

    Note: you must restart your server (e.g. run npm start again) to detect environment variable changes.

提交回复
热议问题