2

I have a react app which has an entrypoint of my app.jsx and I am adding segment.io to my build, however I would like to set it's API key as an process.env variable. I am having trouble with how to do this with webpack because my entry point is not the index.html.

I am trying to see if there is a way so I can (on the index.html) do something like this

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

But I am not sure how to get it so I can process env variables at the index.html level.

In app.jsx I am toggling the code like :

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

and this works fine because I have access to the vars at this point. I would like to also conditionally load the script on the index.html. Anyone know if this is possible? Thanks!

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133

1 Answers1

0

Just load analytics in your JSX file as follow:

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

Your index.html file should look like that:

<!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>