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.

5
  • "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. Commented Aug 22, 2018 at 11:00
  • maybe now it's better Commented Aug 22, 2018 at 11:14
  • Possible duplicate of How to add DOM element script to head section? Commented Aug 22, 2018 at 11:20
  • 1
    Also lots of information here stackoverflow.com/q/610995/125981 Commented Aug 22, 2018 at 11:27
  • Thanks a lot! The last one helped me Commented Aug 22, 2018 at 15:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is that I need to use only inline script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.