gpt4 book ai didi

create-react-app - Vercel 重定向中的环境变量

转载 作者:行者123 更新时间:2023-12-04 10:02:40 27 4
gpt4 key购买 nike

我想将我的 create-react-app 部署到 Vercel。

我在我的 now.json 中定义我的重定向,如下所示:

{
"redirects": [
{ "source": "/api/(.*)", "destination": "BACKEND_URL/$1", "statusCode": 200 }
]
}

目标 URL 取决于在 Vercel 仪表板中定义的环境变量 BACKEND_URL

我正在尝试在以下构建命令中替换重定向中的环境变量:sed -i "s|BACKEND_URL|${BACKEND_URL}|g"now.json && yarn 构建

但不幸的是 now.json 在构建时似乎不可用:

09:54:44.243 sed: can't read now.json: No such file or directory

如何在 Vercel 中启用动态重定向?

最佳答案

这是不可能的,因为读取 now.json 以确定如何构建,因此您不能在构建期间动态生成它。

相反,请考虑使用类似 Next.js 的框架它提供了一个可以读取 RFC 9081 中定义的环境变量的 next.config.js .

npm install next@canary react react-dom
// next.config.js
module.exports = {
experimental: {
async redirects() {
return [{
source: "/api/:path*",
destination: `${process.env.BACKEND_URL}/:path*`,
permanent: false,
}]
}
}
};

https://github.com/zeit/now/discussions/4351

关于create-react-app - Vercel 重定向中的环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61753744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com