React基础框架搭建11-env不同环境配置(基础结束):react+router+redux+axios+Tailwind+webpack

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',
    },
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值