在为基于create-react-app的项目运行npm build之后,在运行时读取环境变量 [英] Reading environment variable in run time after running npm build for a create-react-app based project

查看:288
本文介绍了在为基于create-react-app的项目运行npm build之后,在运行时读取环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React的新手,我将部署一个React项目。 React项目由create-react-app创建,然后生产代码由 npm build构建,并且由Express托管。



在项目中,是对API服务器的一些提取调用,需要对URL进行配置。在开发中,我可以通过在.env文件的环境变量中设置它来做到这一点(例如,REACT_APP_API_URL = http:// somewhere / )并导入到代码中。



但是,似乎这些环境变量在运行 npm build后变为静态,即使执行 REACT_APP_API_URL = http:// otherserver / 节点express_server.js。



<我想问一下 npm build之后是否有任何方法可以为代码提供一些配置,最好是可以从文件或.env中获取,也可以从环境变量中获取。



谢谢。

解决方案

环境变量已嵌入文件在构建步骤中运行,因此在调用 react-scripts build 时需要为它们分配适当的值。



示例

 脚本:{
start: cross- env REACT_APP_API_URL = http:// somewhere / react-scripts start,
build:跨环境REACT_APP_API_URL = http:// otherserver / react-scripts build,
}


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 (e.g., 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",
}

这篇关于在为基于create-react-app的项目运行npm build之后,在运行时读取环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆