React:使用环境变量

时间:2016-06-22 18:34:42

标签: reactjs

如何在React应用程序中使用{{1}}中定义的环境变量?我在生产中有两个React应用程序(它们是相同的项目,因此它们具有相同的代码),但是它们需要请求不同的API主机,并且我认为env变量可以解决这个问题。

2 个答案:

答案 0 :(得分:22)

使用webpack.DefinePlugin。假设您在FOO中导出BAR.bash_profile,那么您的webpackconfig应如下所示:

const config = {
  entry: 'somescript',
  // ...
  module: {
    // ...
  },
  // ...
  plugins: [
    // ... your plugins
    new webpack.DefinePlugin({
      'process.env':{
        'FOO': process.env.FOO,
        'BAR': process.env.BAR
      }
    })
  ],
  // ...
}

您可以通过process.env.FOO&编译时在编译时访问js中的那些内容。 process.env.BAR

资源:https://github.com/topheman/webpack-babel-starter

答案 1 :(得分:-1)

将环境变量存储在index.html中!

如果将index.html视为包含环境特定值的部署清单,则可以在每个环境中使用相同版本的资产(js,css)!

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="https://assets.myapp.com/favicon.ico">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="https://assets.myapp.com/manifest.json">
    <title>React App</title>
    <script>
      env = {
        // Add your environment variables here
        api: "https://staging-api.myapp.com"
      };
    </script>
    <link href="https://assets.myapp.com/static/css/main.6bd13355.chunk.css" rel="stylesheet">
</head>
<body>
    <div id="root"></div>
    <script src="https://assets.myapp.com/static/js/1.a700ff87.chunk.js"></script>
    <script src="https://assets.myapp.com/static/js/main.3ec5cdc6.chunk.js"></script>
</body>
</html>

在您的代码中直接引用值:myApi = window.env.api;

https://immutablewebapps.org

中阅读有关此方法的更多文档。
相关问题