0

I have index.html where I want to load hotjar tracking code (only inline script), but it depends on the env variable. I tried to use webpack DefinePlugin

new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),

and get this env, but I can get it only from react component.

componentWillMount() {
    const env = process.env.NODE_ENV;
    document.getElementById('hotjar').innerHTML = env === 'production' ? "...script1" : "...script2" 
  }

Then I used 'innerHTML' to put my script to the index.html, but it doesn't work as I expected.

Here is the body of index.html

<body>
 <div id="root"></div>
  <script src="/dist/bundle.js"></script>
  <script id="hotjar">
  </script>
</body>

So, I need to get it within some script on index.html or something like this? Can someone help me? Thanks.

Oloji
  • 175
  • 1
  • 11
  • "env variable", "get this env, but I can get it only from react component" , what is that and can you please clarify? What platform? Please provide something that you have tried so we can help fix it rather than simply "I tried several things" and "I am uncertain what to do". "hotjar tracking code" - what code, we see no code. – Mark Schultheiss Aug 22 '18 at 11:00
  • maybe now it's better – Oloji Aug 22 '18 at 11:14
  • Possible duplicate of [How to add DOM element script to head section?](https://stackoverflow.com/questions/18784920/how-to-add-dom-element-script-to-head-section) – Mark Schultheiss Aug 22 '18 at 11:20
  • 1
    Also lots of information here https://stackoverflow.com/q/610995/125981 – Mark Schultheiss Aug 22 '18 at 11:27
  • Thanks a lot! The last one helped me – Oloji Aug 22 '18 at 15:14

1 Answers1

0

You can use different files for each environment. Like tracking_test.js tracking_prod.js and use webpack to pick the appropriate file while building and rename it to tracking.js. Refer the tracking.js in the html file. By this means, you don't ship the unnecessary code.

If you want to continue with your modifying innerHTML route, look into https://github.com/nfl/react-helmet They have nicer APIs for the same.

Prasanna
  • 10,956
  • 2
  • 28
  • 40