Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Use environment variables

Tags:

reactjs

How can I use environment variables defined in .bash_profile in a React application? I have two React apps in production (they're the same project, so they have the same code), but they need to request to different API hosts, and I figured env variables could do the trick.

like image 802
sauronnikko Avatar asked Jun 22 '16 18:06

sauronnikko


People also ask

Can React use environment variables?

Create React App supports custom environment variables without the need to install any other packages. There are two methods of adding environment variables: Through the shell (temporary, lasts as long as shell session last, and varies depending on the OS type).

How do you access system environment variables in react JS?

Method 1: Using npm scripts to set environment variables Let's add some environment variables with a --env flag in our scripts. We've added the --env. API_URL= part in both scripts. Now, run your npm run dev command, go to your React component and use the process.


1 Answers

Use webpack.DefinePlugin. Say you exported FOO and BAR in your .bash_profile, then your webpackconfig should look like:

const config = {
  entry: 'somescript',
  // ...
  module: {
    // ...
  },
  // ...
  plugins: [
    // ... your plugins
    new webpack.DefinePlugin({
      'process.env':{
        'FOO': process.env.FOO,
        'BAR': process.env.BAR
      }
    })
  ],
  // ...
}

You will be able to access those in your js at compile time via process.env.FOO & process.env.BAR

Resource: https://github.com/topheman/webpack-babel-starter

like image 72
topheman Avatar answered Oct 25 '22 12:10

topheman