只是另一个 React 问题。 我想全局存储一些 URL 信息并按环境(开发、生产等...)划分。
网上搜了一下,一般的方法是react自然支持的.env文件。
我已经创建了一个 .env 和一个 .env.development,所以第一个是生产文件,第二个是开发文件。
在文件中,我将我的配置放在:
# .env.development
REACT_APP_TEST=newyork
我尝试打印值:
console.log(process.env);
console.log(process.env.REACT_APP_TEST);
我得到的是:
Object
NODE_ENV:"development"
PUBLIC_URL:""
第二个未定义。
问题出在哪里?
最佳答案
如果您正在使用 create-react-app,您将需要更新您的 env.js
以在构建中包含您的新环境变量。
函数 getClientEnvironment(publicUrl)
设置注入(inject)到构建中供您使用的环境变量。在这里,您可以像这样添加自定义环境变量:
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
CUSTOM: process.env.CUSTOM || 'fallback'
}
更新:
如果您不使用 CRA,您可以使用 webpack DefinePlugin做同样的事情。
更新 2:
@DimitarChristoff 指出您应该使用 REACT_APP_*
格式来声明环境变量。如果您在 env 变量前添加 REACT_APP_
,CRA 将自动获取它并将其添加到 Webpack DefinePlugin:
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
关于javascript - ReactJS + 环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505641/