npm install dotenv
npm install env-cmd
1、创建不同的 .env 文件
.env.development:用于开发环境
.env.test:用于测试环境
.env.production:用于生产环境
//.env.development
REACT_APP_API_BASE_URL=http://localhost:3000
REACT_APP_ENV=development
REACT_APP_TIMEOUT=10000
//.env.test
REACT_APP_API_BASE_URL=http://test.example.com/api
REACT_APP_ENV=test
REACT_APP_TIMEOUT=5000
//.env.production
REACT_APP_API_BASE_URL=https://api.example.com
REACT_APP_ENV=production
REACT_APP_TIMEOUT=10000
2、在 package.json 中配置脚本
"scripts": {
"start:dev": "env-cmd -f .env.development react-scripts start",
"start:test": "env-cmd -f .env.test react-scripts start",
"start:prod": "env-cmd -f .env.production react-scripts start"
}
3、使用:
console.log(process.env.REACT_APP_API_BASE_URL); // 输出 API 基础路径
使用场景:
api中的url:
// 创建 Axios 实例
const apiClient = axios.create({
baseURL: process.env.REACT_APP_API_BASE_URL, // 使用环境变量作为基础路径
timeout: parseInt(process.env.REACT_APP_TIMEOUT, 10) || 10000, // 超时时间
headers: {
'Content-Type': 'application/json',
},
});