Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use environment variables with webpack+reactjs?

I am compiling my Reactjs files using webpack. In my project I need to make API calls to the backend.

Now I have 3 environments which would local, development and production.

So i have a constants.jsx file in which I have declared following:-

export const url= 'http://localhost:8002/api/v0';

So in my components I import the url from above and use them to call APIS, but how I need to change above variable based on whether it is local, dev or prod.

How do I implement above?

like image 404
Harkirat Saluja Avatar asked Jul 03 '16 18:07

Harkirat Saluja


1 Answers

So I was trying few things and solved the above by doing following:

In a Webpack config add a DefinePlugin. Following is my webconfig:

plugins: [
  new BundleTracker({filename: './webpack-stats.json'}),
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(process.env.environment),
    }
  })
],

Now while compiling we use the following commands:

environment=local webpack (for local)
environment=development webpack(for dev)
environment=production webpack(for prod)

Now if you see we set 'NODE_ENV' with the cli input so when 'NODE_ENV' is production as value, the webpack automatically minifies your output bundle.

Now say we have API url declared in a file(I had Constants.jsx), so we add following to constants.jsx. We can read the NODE_ENV set in webpack config in this Constants.jsx and import them in your components from where APIS are called by exporting it from here.

const api_url = function () {
  let api_url = '';
  if (process.env.NODE_ENV == 'local') {
    api_url = 'http://localhost:8002/api/v0';
  } else if (process.env.NODE_ENV == 'development') {
    api_url = 'https://development/api/v0';
  } else if (process.env.NODE_ENV == 'production') {
    api_url = 'https://production/api/v0';
  }
  return api_url;
}

export const url = api_url();
like image 105
Harkirat Saluja Avatar answered Sep 29 '22 19:09

Harkirat Saluja