webpack,在index.html中处理env变量

时间:2017-03-08 20:09:14

标签: javascript html reactjs webpack segment-io

我有一个具有app.jsx入口点的反应应用程序,我将segment.io添加到我的构建中,但是我想将它的API密钥设置为process.env变量。我在使用webpack时遇到问题,因为我的入口点不是index.html。

我试图看看是否有办法让我(在index.html上)做这样的事情

<script type="text/javascript">
  ..segment script loading here + (process.env.MY_SEGMENT_KEY)}();
 </script>

但我不知道如何获得它所以我可以在index.html级别处理env变量。

在app.jsx中,我正在切换代码:

if (process.env.MY_SEGMENT_KEY) {
....
}

这很好,因为此时我可以访问变量。我还想有条件地在index.html上加载脚本。任何人都知道这是否可行?谢谢!

1 个答案:

答案 0 :(得分:0)

只需在您的JSX文件中加载分析,如下所示:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

if (process.env.MY_SEGMENT_KEY) {
  window.analytics.load(process.env.MY_SEGMENT_KEY);
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

您的index.html文件应如下所示:

<!DOCTYPE html>
<html>
  <head>
    ...
    <title>My App</title>
    <script type="text/javascript">
      !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="4.0.0";
      }}();
    </script>
  </head>
  <body>
    <div id="root">
    </div>
  </body>
</html>