在前端代码中访问NODE_ENV是否有意义? [英] Does accessing NODE_ENV make sense in front end code?
问题描述
我有一个正在部署的react/node应用程序.组件之一尝试访问NODE_ENV以确定要使用的主机URL(localhost或heroku).
I have a react/node app that I'm deploying. One of the components attempts to access NODE_ENV in order to determine which host URL to use (localhost or heroku).
我现在意识到,即使将NODE_ENV设置为生产版本,由于环境不是节点,因此在浏览器上下文中它始终是未定义的".
I now realize that even though NODE_ENV is being set to production, it's always 'undefined' in the browser context, because the environment is not node.
由于无法从react组件访问NODE_ENV,如何动态设置主机服务器?
Since I can't access NODE_ENV from my react component, how do I dynamically set the host server?
推荐答案
在API URL之类的内容中使用NODE_ENV
变量是一种好习惯.
It's a good practice to use NODE_ENV
variables for things like API URL.
如果您使用的是创建-react-app ,所有以REACT_APP_
开头的环境变量都应该已经可以通过process.env.REACT_APP_VARIABLE_NAME
访问.
您可以先按REACT_APP_TEST=5 npm start
然后按console.log(process.env.REACT_APP_TEST)
.
If you used create-react-app, all environment variables starting with REACT_APP_
should already be accessible with process.env.REACT_APP_VARIABLE_NAME
.
You can try REACT_APP_TEST=5 npm start
then console.log(process.env.REACT_APP_TEST)
.
如果您不使用create-react-app
,则必须将其导入Webpack配置中.
If you are not using create-react-app
, you have to import them in your webpack config.
您还可以选择使用 dotenv .
这篇关于在前端代码中访问NODE_ENV是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!