How to use html-webpack-plugin variable inside <script>?

Viewed 788

I am trying to assign variable inside <script> tag by means of html-webpack-plugin where the variable is located. I can easily use it inside html tags like title <%= htmlWebpackPlugin.options.applicationId %>

My html-webpack-plugin looks like :

new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      inject: true,
      applicationId : process.env.APPLICATION_ID ?process.env.APPLICATION_ID : 1,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: false
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),

And I want to use variable applicationId on index.html page with following script :

<script type="text/javascript">
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          document.write(xhr.responseText);
        }
      };
     var appId = <%= htmlWebpackPlugin.options.applicationId %>;
   xhr.open("GET","https://somesite.com/NavigationApi/api/content/get?applicationId=" + appId,false);
      xhr.send(null);
    </script>
1 Answers

You can set a hidden input and set the appId there, then you can retrieve that value with javascript (make sure to do that inside jquery's onload event or using DOMContentLoaded if you want to use vanilla JS), hope this helps.

Related