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?

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

const api_url function seems a bit verbose? can you do this in any other way?
verbose? can you be a bit more elaborate?
Compare this for example with: stackoverflow.com/questions/38164102/…
"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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.