How to use environment variables with webpack+reactjs?

梦想的初衷 提交于 2019-12-23 09:37:49

问题


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:


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

In our 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();


来源:https://stackoverflow.com/questions/38172914/how-to-use-environment-variables-with-webpackreactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!