简体   繁体   中英

Reading environment variable in run time after running npm build for a create-react-app based project

I am new to React and I am going to deploy a React project. The React project is created by create-react-app, then the production code is built by "npm build" and it is host by Express.

In the project, there are some fetch call to a API server, which the URL is want to be configurable. In development, I am able to do this by setting it in the environment variables in the file .env (eg, REACT_APP_API_URL= http://somewhere/ ) and imported in the codes.

However, seems those environment variables becomes static after running "npm build", I am not able to change it anymore, even by doing something like "REACT_APP_API_URL= http://otherserver/ node express_server.js" when I start the server.

I would like to ask if there is any way to source some configurations for the codes after "npm build", it is the best if it can be source from a file or .env, from environment variables is ok for me too.

Thank you.

The environment variables gets embedded in the files in the build step, so you need to assign the proper values to them when you call react-scripts build .

Example

"scripts": {
  "start": "cross-env REACT_APP_API_URL=http://somewhere/ react-scripts start",
  "build": "cross-env REACT_APP_API_URL=http://otherserver/ react-scripts build",
}

I found a way of fetching a custom conf.json file from a backend and apply the parameters in react as follows in index.tsx file of my react app:

const CURR_ENV = process.env.REACT_APP_ENV;

console.log('ENV: ' + CURR_ENV)

if (CURR_ENV === 'prod') {
    console.log("fetching conf.json ...")
    fetch('conf.json')
        .then(response => response.json())
        .then(data => {
            console.log("data=" + JSON.stringify(data))
            const amplify = data['amplify'];
            console.log("amplify=" + JSON.stringify(amplify))
            Auth.configure(amplify);
            Auth.configure(amplify);

            const backendUrl = data['backendUrl'];
            console.log("backendUrl=" + JSON.stringify(backendUrl))
            localStorage.setItem('backend_url', backendUrl);
            console.log("successfully configured amplify and apigw")
        })
        .catch(error => console.error(JSON.stringify(error)))
}
else {
    localStorage.setItem('backend_url', process.env.REACT_APP_BACKEND_URL?process.env.REACT_APP_BACKEND_URL:"");
    Amplify.configure(awsmobile);
    Auth.configure(awsmobile);
}

ReactDOM.render(
  <Router>
      <div>
          <Route path="/" component={App}/>
      </div>
  </Router>,
  document.getElementById('root')
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM