【发布时间】:2021-10-25 12:49:29
【问题描述】:
我想在更改环境时动态切换外部后端 API 的基本 url。
例如.env.local=local.com, .env.staging=staging.com, .env.production=production.com
为此,我使用 axios 进行 API 调用,并且使用 axios 的实例,其中 baseURL 取决于项目的当前环境。 例如
const axiosInstance = axios.create({
baseURL: process.env.BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
而我在package.json 的脚本如下:
"scripts": {
"dev": "next dev",
"dev:staging": "env-cmd -f .env.staging next dev",
"dev:production": "env-cmd -f .env.production next dev",
"build": "next build",
"build:staging": "env-cmd -f .env.staging next build",
"build:production": "env-cmd -f .env.production next build",
"start": "next start",
"start:staging": "env-cmd -f .env.staging next start",
"start:production": "env-cmd -f .env.production next start"
},
但它总是加载 .env.development 并且 axiosInstance 没有获取 baseUrl。
【问题讨论】:
标签: reactjs axios environment-variables next.js