【发布时间】:2023-03-15 15:30:01
【问题描述】:
我正在将一个 React 应用程序(版本 15.4.2)部署到 Heroku,但我在访问环境变量时遇到了问题 - 任何澄清将不胜感激。
我最初使用create-react-app 启动了这个应用程序,但最终将其弹出以便我可以进行更多控制。
在config/env.js 中,我设置了我想要的变量API_URL,如下所示:
function getClientEnvironment(publicUrl) {
var processEnv = Object
.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce((env, key) => {
env[key] = JSON.stringify(process.env[key]);
return env;
}, {
'NODE_ENV': JSON.stringify(
process.env.NODE_ENV || 'development'
),
'PUBLIC_URL': JSON.stringify(publicUrl),
'API_URL': JSON.stringify(
process.env.API_URL || 'http://localhost:4000/api/v1'
)
});
return {'process.env': processEnv};
}
module.exports = getClientEnvironment;
并且这个模块在webpack.config.prod.js(释义)中被引用...
var env = getClientEnvironment(publicUrl);
module: {
plugins: [
new webpack.DefinePlugin(env)
]
}
最后,我想在 src/static/scripts/fetch.js 中的脚本中引用 API_URL:
fetch(`${API_URL}${url}`, {
method: 'GET',
headers: headers()
})
.then(parseResponse)
但是当我尝试将其推送到 Heroku 时,它因错误而失败
remote: 24:21 error 'API_URL' is not defined no-undef
我是否错误地设置了API_URL 变量?或者我没有正确部署应用程序?尽管我退出了该应用程序,但我仍然像部署未退出的 create-react-app 应用程序一样部署它 - https://blog.heroku.com/deploying-react-with-zero-configuration - 但也许这还不够。
【问题讨论】:
标签: reactjs heroku environment-variables