8

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?

Harkirat Saluja
  • 7,768
  • 5
  • 47
  • 73
  • 3
    See http://stackoverflow.com/questions/30030031/passing-environment-dependent-variables-in-webpack for how to pass variables in webpack.config.js. – Dennis Shtatnov Jul 03 '16 at 18:15

1 Answers1

9

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();
ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
Harkirat Saluja
  • 7,768
  • 5
  • 47
  • 73
  • const api_url function seems a bit verbose? can you do this in any other way? – Capuchin Jul 15 '16 at 08:34
  • verbose? can you be a bit more elaborate? – Harkirat Saluja Jul 15 '16 at 08:35
  • Compare this for example with: http://stackoverflow.com/questions/38164102/change-hard-coded-url-constants-for-different-environments-via-webpack – Capuchin Jul 15 '16 at 08:43
  • `"scripts": { "build": "cross-env NODE_ENV=development webpack" ` this is my build script for dev , Can you tell how to run different script for different env. I am running it throuh maven pom.xml – Shrikant Dande May 09 '18 at 09:55