Insert inline script to the index.html with env variable

1.3k Views Asked by At

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.

1

There are 1 best solutions below

1
On

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.