我是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=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=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=somewhere/ react-scripts start", "build": "cross-env REACT_APP_API_URL=otherserver/ react-scripts build", }
更多推荐
在为基于create
发布评论