在 .env 中添加开发环境变量
注意:此功能适用于
react-scripts@0.5.0及更高版本。
要定义永久环境变量,请在项目的根目录中创建名为 .env 的文件:
REACT_APP_SECRET_CODE=abcdef
注意:你必须以
REACT_APP_开头创建自定义环境变量。除了NODE_ENV之外的任何其他变量都将被忽略,以避免意外地在可能具有相同名称的计算机上公开私钥。更改任何环境变量都需要重新启动正在运行的开发服务器。
.env 文件 应该 检入源代码控制(排除 .env*.local)。
还可以使用哪些其他 .env 文件?
注意:此功能 适用于
react-scripts@1.0.0及更高版本。
.env:默认。.env.local:本地覆盖。除 test 之外的所有环境都加载此文件。.env.development,.env.test,.env.production:设置特定环境。.env.development.local,.env.test.local,.env.production.local:设置特定环境的本地覆盖。
左侧的文件比右侧的文件具有更高的优先级:
npm start:.env.development.local,.env.development,.env.local,.envnpm run build:.env.production.local,.env.production,.env.local,.envnpm test:.env.test.local,.env.test,.env(注意没有.env.local)
如果机器没有明确设置它们,这些变量将作为默认值。
举例:
1.在项目根目录新建.env.development.local,并定义环境变量:
REACT_APP_RECORDS_API_URL=http://localhost:3004
注意:每次改变.env.development.local后需要进行npm start重启才能生效。

2.在RecordsAPI.js文件中定义一个系统变量REACT_APP_RECORDS_API_URL调用失败时使用的默认值,并将GET方法也定义一个方法方便调用。
import axios from 'axios';
const api = process.env.REACT_APP_RECORDS_API_URL || "http://localhost:5000"
export const getAll = () => axios.get(`${api}/records`)
3.在Records_axios.js文件中调用getAll()方法。
import React,{ Component } from "react";
import Record from './Record';
import * as RecordsAPI from '../utils/RecordsAPI.js'
class Records_axios extends Component{
constructor() {
super();
this.state = {
error: null,
isLoaded: false,
records: []
}
}
componentDidMount(){
RecordsAPI.getAll().then(
response => this.setState({
records: response.data,
isLoaded: true,
}),
).catch(
error => this.setState({
isLoaded: true,
error,
}),
)
}
render(){
const {error, isLoaded, records} = this.state;
if (error) {
return <div>Error: {error.message}</div>;
}
else if (!isLoaded){
return <div>Loading...</div>;
}
else {
return (
<div>
<h2>Records</h2>
<table className="table table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Title</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{records.map((record, id) => <Record key={record.id} record={record} />)}
</tbody>
</table>
</div>
);
}
}
}
export default Records_axios;
本文介绍了如何在React项目中使用.env文件来定义和管理开发环境变量,包括默认的.env文件及其优先级,以及针对不同环境(如development、test、production)的.env文件。通过在.env.development.local中设置环境变量,例如REACT_APP_RECORDS_API_URL,可以实现API URL的本地配置,并在组件中使用这些变量进行API调用。
3629

被折叠的 条评论
为什么被折叠?



