简体   繁体   中英

ReactJS + Environment Variables

Just another React Question. I want to store some URL information globally and divided by environment (dev, production etc...).

Searching on web, the usual method is .env files that are naturally supported by react.

I have create a .env and a .env.development so the first will be the production and the second the development file.

Inside the file, I put my configuration like:

# .env.development
REACT_APP_TEST=newyork

I tried to print the values with:

console.log(process.env);
console.log(process.env.REACT_APP_TEST);   

What I get is:

Object
  NODE_ENV:"development"
  PUBLIC_URL:""

The second is undefined.

Where is the problem?

If you are using create-react-app, you will need to update your env.js to include your new environment variable in the build.

The function getClientEnvironment(publicUrl) sets the environment variables that get injected into the build for your use. Here, you can add your custom env variable like so:

  {
    // 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'
  }

UPDATE:

If you're not using CRA, you can use the webpack DefinePlugin to do the same thing.

UPDATE 2:

@DimitarChristoff pointed out that you should use the REACT_APP_* format for declaring env variables. If you prepend your env variable with REACT_APP_ , CRA will automatically pick it up and add it to the 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;

It was more simple than expected. The .env files has to be placed in the root of the project NOT in the SRC folder.

That's all!

In general Webpack case, you can use webpack's DefinePlugin to define variables to be accessible across app.

In CRA (Create-React-App), you can add the environment variable in env.js file.

Using env.js is same as making your own config.js file where you create your config variable with a value either from process.env or use a default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM