ReactJS +环境变量

Ret*_*ime 2 javascript reactjs create-react-app

只是另一个反应问题.我想在全局存储一些URL信息,并按环境(开发,生产等)划分.

在网上搜索,通常的方法是反应自然支持的.env文件.

我创建了一个.env和一个.env.development,所以第一个是生产,第二个是开发文件.

在文件中,我把我的配置如下:

# .env.development
REACT_APP_TEST=newyork
Run Code Online (Sandbox Code Playgroud)

我尝试用以下方法打印值:

console.log(process.env);
console.log(process.env.REACT_APP_TEST);   
Run Code Online (Sandbox Code Playgroud)

我得到的是:

Object
  NODE_ENV:"development"
  PUBLIC_URL:""
Run Code Online (Sandbox Code Playgroud)

第二个是未定义的.

问题出在哪儿?

Cha*_*nda 5

如果您使用的是create-react-app,则需要更新您的内容env.js以在构建中包含新的环境变量.

该函数getClientEnvironment(publicUrl)设置注入构建中的环境变量供您使用.在这里,您可以像这样添加自定义env变量:

  {
    // 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'
  }
Run Code Online (Sandbox Code Playgroud)

更新:

如果您不使用CRA,则可以使用webpack DefinePlugin执行相同的操作.

更新2:

@DimitarChristoff指出你应该使用这种REACT_APP_*格式来声明env变量.如果你在前面加上你的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;
Run Code Online (Sandbox Code Playgroud)