如何在 webpack+reactjs 中使用环境变量? [英] How to use environment variables with webpack+reactjs?

查看:36
本文介绍了如何在 webpack+reactjs 中使用环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 webpack 编译我的 Reactjs 文件.在我的项目中,我需要对后端进行 API 调用.

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

现在我有 3 个环境,分别是本地、开发和生产.

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

所以我有一个constants.jsx文件,我在其中声明了以下内容:-

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

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

所以在我的组件中,我从上面导入 url 并使用它们来调用 APIS,但是我需要如何根据它是本地、开发还是生产来更改上面的变量.

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.

我如何实现上述内容?

推荐答案

所以我尝试了一些事情并通过执行以下操作解决了上述问题:-

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

在我们的 webpack 配置中添加一个 DefinePlugin.以下是我的网络配置:-

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)

现在,如果您看到我们使用 cli 输入设置了 'NODE_ENV',那么当 'NODE_ENV' 作为生产值时,webpack 会自动缩小您的输出包.

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.

现在假设我们在文件中声明了 API url(我有 Constants.jsx),所以我们将以下内容添加到 constants.jsx.我们可以在这个 Constants.jsx 中读取 webpack 配置中设置的 NODE_ENV,并通过从这里导出 APIS 将它们导入到您的组件中.

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

这篇关于如何在 webpack+reactjs 中使用环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆